Handler解析

Handler 原理:

首先sendMessage()以及 sendMessageDelayed()最后调用的都是 sendMessageDelayed(),接着开始总体流程
遍历链表: 首先判断链表里有没有message,如果里面是空的或者传入的msg执行的时间比头message要早,则把msg放到链表的头部,( 比如send两次message,先执行的有延时,后执行的没延时,这个时候就要把后执行的message放到最前面) 接着遍历链表,根据执行的事件去调整message的位置:

第一次添加数据到队列中,或者当前 msg 的时间小于 mMessages 的时间

// p为队列中头部msg
if (p == null || when == 0 || when < p.when) {

        // New head, wake up the event queue if blocked.

        // 把当前 msg 添加到链表的第一个

        msg.next = p;

        mMessages = msg;

        needWake = mBlocked;

} else {

        // 不是第一次添加数据,并且 msg 的时间 大于 mMessages(头指针) 的时间

        // Inserted within the middle of the queue.  Usually we don't have to wake

        // up the event queue unless there is a barrier at the head of the queue

        // and the message is the earliest asynchronous message in the queue.

        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 插入到列表中

        msg.next = p; // invariant: p == prev.next

        prev.next = msg;

}

Looper

Looper是通过不断循环去获取message的,要使用handler,子线程中必须调用looper.prepare()以及 looper.loop()。主线程中默认有一个looper,ActivityThread中系统已经初始化了一个looper,下面是具体逻辑代码
public static void loop() {

    final Looper me = myLooper();

    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;

        }

        try {

            // 通过 target 去 dispatchMessage 而 target 就是绑定的 Handler
            // 到这里也就完成了消息的传递流程

            msg.target.dispatchMessage(msg);

        } finally {

            // 消息回收循环利用

            msg.recycleUnchecked();

        }

    }

}

在这里loop的死循环涉及到pipe知识就不深入探讨,如下图

image.gif
image.png

你可能感兴趣的:(Handler解析)