handler流程

1、Loop.prepare():创建Loop对象,初始化Loop中的MessageQueue跟当前的Thread;

private static void prepare(boolean quitAllowed) {

    if (sThreadLocal.get() != null) {

        throw new RuntimeException("Only one Looper may be created per thread");

    }

    sThreadLocal.set(new Looper(quitAllowed));

}

2、Loop.loop():拿到当前线程Loop对象,在拿到Loop中的消息队列,for循环轮询遍历消息队列,不断调用MessageQueue的next方法,取出消息;

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;

for (;;) {

    Message msg = queue.next(); // might block

    if (msg == null) {

        // No message indicates that the message queue is quitting. return;

    }

    msg.target.dispatchMessage(msg);

}

3、创建handler对象:创建handler对象时,会拿到当前线程的Loop对象,除了Main线程,其他线程都得初始化Loop对象,否则会报错。通过Loop对象,把handler跟所属线程的消息队列关联起来;

public Handler(Callback callback, boolean async) {

    mQueue = mLooper.mQueue;

}

4、发送消息:实际上是把消息加到消息队列中,但在这一步之前,会把handler对象赋值给msg的target属性;

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

    msg.target = this;

    if (mAsynchronous) {

        msg.setAsynchronous(true);

    }

    return queue.enqueueMessage(msg, uptimeMillis);

}

5、接收消息:将消息加入到了消息队列,通过Loop的轮询,就能取出当前加入到消息队列的消息。最终把消息分发给消息体的target属性(调用了Handler的dispatchMessage方法),这个target实际上就是发出消息的handler对象;

public void dispatchMessage(Message msg) {

    if (msg.callback != null) {

        handleCallback(msg);

    } else {

        if (mCallback != null) {

            if (mCallback.handleMessage(msg)) {

                return;

            }

        }

        handleMessage(msg);

    }

}

6、处理消息:最终来到了Handler的dispatchMessage方法,方法里会判断callback对象是否为空,如果为空,就调用handleMessage方法,就是我们平时创建handler时重写的handleMessage方法。

handleMessage(msg)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 【今天讲故事】 使用思维导图3年多 先后做了100多张图 思维导图给我带来太多的改变 今天来说说我和它的故事 01...
    朱朱蜗牛阅读 4,419评论 3 3
  • 阳阳的作业是听写词语,我负责报听写。 前面的词都写得很顺利,写到“开垦”的“垦”字时,阳阳犹豫了,思考了一会写了“...
    舒芯阅读 1,774评论 0 0
  • 如果问我,这世界上温暖人心的是什么,我现在肯定会毫不犹豫的告诉你,那是爱,唯有爱才能够真正感动我们的心,唯有爱才能...
    旅途觉醒阅读 2,490评论 0 0

友情链接更多精彩内容