Handler + Looper + MessageQueue详解

一、使用详解

(1)Handler使用

//创建一个带有Looper的线程
class LooperThread extends Thread{
    @Override
    public void run() {
        Looper.prepare();
        Looper.loop();
    }
}

//在主线程中创建,自动绑定主线程Looper
private Handler uiHandler = new Handler() {
    //重写Handler的处理消息的方法handleMessage()
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case 1:
                break;
        }
    }
};
//获取子线程实例
LooperThread looperThread = new LooperThread();
//开启子线程
looperThread.start();
//获取子线程Looper
Looper loop = looperThread .getLooper();
//手动绑定子线程Looper
private Handler mHandler = new Handler(loop) {
    //重写Handler的处理消息的方法handleMessage()
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case 1:
                break;
        }
    }
};
//发送消息
Message message = new Message();
message.what = 1;
message.obj = "result";
uiHandler.sendMessage(message )
mHandler.sendMessage(message )

(2)Handler构造方法

  • Handler():构造函数将通过调用Looper.myLooper()获取当前线程绑定的Looper对象,将该Looper对象保存到名为mLooper的成员字段中。
  • Handler(Looper looper):直接将该Looper保存到名为mLooper的成员字段中。
  • Handler(Callback callback):构造函数传递了Callback对象,Callback是Handler中的内部接口,需要实现其内部的handleMessage方法。
  • Handler(Looper looper, Callback callback)
    处理Message消息,通过实现Handler.Callback的handleMessage方法或重写Handler本身的handleMessage方法

多线程实现:向Thread的post函数传入一个Runnable对象者重写Thread本身的run方法。

二、源码解析

(1)Handler源码
Handler的创建

    public Handler() {
        this(null, false);
    }

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        //获取当前线程的Looper对象
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        //获取当前Looper的消息队列MessageQueue对象
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

Handler.sendMessage发送消息

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        //Handler所绑定的消息队列MessageQueue
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        //将Message的target绑定为当前的Handler
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //通过queue.enqueueMessage(msg, uptimeMillis)我们将Message放入到消息队列中。
        return queue.enqueueMessage(msg, uptimeMillis);
    }

Handler.dispatchMessage发送消息到Handler

    //派发消息到对应的Handler实例。根据传入的msg作出对应的操作
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //使用了post发送消息,则执行handleCallback方法,回调Runnable复写的run方法
            handleCallback(msg);
        } else {
            //使用了sendMessage发送消息,则执行handleMessage,回调复写的handleMessage
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

(2)Looper创建源码
Looper.prepare()创建Looper,当前线程和Looper就进行了双向的绑定

    //Looper对象中通过sThreadLocal就可以找到其绑定的线程
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        //1个线程中只能对应1个Looper实例
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //创建Looper对象存放在ThreadLocal变量中
        sThreadLocal.set(new Looper(quitAllowed));
    }
    
    private Looper(boolean quitAllowed) {
        //创建消息队列对象
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Looper.loop()循环获取MessageQueue中消息Message

    public static void loop() {
        //获取当前线程所绑定的Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获取当前线程所关联的消息队列
        final MessageQueue queue = me.mQueue;

        //code...

        //消息循环
        for (;;) {
            //从消息队列中取出消息
            Message msg = queue.next(); // might block
            //若取出的消息为空,则线程阻塞
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            //code...
            try {
                //Message所关联的Handler通过dispatchMessage方法让Handler处理该Message
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            //code...
            //释放消息占据的资源
            msg.recycleUnchecked();
        }
    }

Looper类还提供了一些有用的方法

    //获取当前线程的Looper
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
    //获取looper对象所属线程
    public Thread getThread() {
        return mThread;
    }
    //结束looper循环
    public void quit() {
        // 创建一个空的message,它的target为NULL,表示结束循环消息  
        Message msg = Message.obtain();
        // 发出消息  
        mQueue.enqueueMessage(msg, 0);
}

(3)MessageQueue源码
MessageQueue.enqueueMessage将一个Message放入到消息队列MessageQueue中

    boolean enqueueMessage(Message msg, long when) {
        //code...
        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            //判断消息队列里有无消息
            if (p == null || when == 0 || when < p.when) {
                //消息队列无消息将当前插入的消息作为队头,若此时消息队列处于等待状态,则唤醒
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //消息队列里有消息,则根据消息创建的时间 插入到队列中
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

MessageQueue.next从消息队列MessageQueue中阻塞式地取出一个Message

Message next() {
        //code...
        //确定消息队列中是否还有消息。从而决定消息队列应处于出队消息状态还是等待状态
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //若是nextPollTimeoutMillis为-1,此时消息队列处于等待状态
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                //从消息队列中取出消息:按创建Message对象的时间顺序
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    //消息队列中已无消息,则将nextPollTimeoutMillis参数设为-1。下次循环时,消息队列则处于等待状态
                    nextPollTimeoutMillis = -1;
                }
                //code...
            }
            //code...
        }
    }

(4)Message源码

    //Message内部维护了一个Message池,用于Message消息对象的复用
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        //若池内无消息对象可复用,则还是用关键字new创建
        return new Message();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容