Handler 底层原理

3,078 阅读3分钟

Handler 存在的意义?

线程通信,消息管理?这只是 Handler 的附带功能。Handler 是 Android 的基础,维持了 App 运行,所有的代码都运行在 Handler 之上

设计思路

就像一个传送带, Hander 负责添加消息,Looper 就像传送带在不停的转动并依次取出 MessageQueue 中的消息

飞书20220110-161029.png

源码

  • Looper:一个线程对应一个 Loopper,用于从 MessageQueue 中取出消息,创建 Looper 对象的同时会创建 MessageQueue 对象。Looper 创建后调用 loop() 方法开启消息循环
//构造函数是 private 类型,外部类只能通过 prepare() 方法创建 Looper 对象
private static void prepare(boolean quitAllowed) {
    //判断当前线程是否创建了 Looper 对象
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //保存 Looper 对象
    sThreadLocal.set(new Looper(quitAllowed));
}

//创建 Looper 对象
private Looper(boolean quitAllowed) {
    //创建 MessageQueue 对象
    mQueue = new MessageQueue(quitAllowed);
    //当前线程, Looper 对象会保存在线程的 ThreadLocalMap 类型的属性中
    mThread = Thread.currentThread();
}

//开启循环
public static void loop() {
    ...
    循环处理消息
    for (;;) {
        if (!loopOnce(me, ident, thresholdOverride)) {
            return;
        }
    }
    ...
}

//取消息
private static boolean loopOnce(final Looper me,
        final long ident, final int thresholdOverride) {
    //取出链表头部消息
    Message msg = me.mQueue.next(); // might block
    //msg 为空表示退出应用
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return false;
    }
    ...
    //消息处理,最终出发 handler 的 handleMessage 方法
    msg.target.dispatchMessage(msg);
    ...
}
  • ThreadLocal ThreadLocal 可以理解成一个工具类,数据实际存在 ThreadLocalMap 中,每一个线程有一个 ThreadLocalMap对象。调用 set 方法存储数据, get 方法获取数据,ThreadLocal 为 Map 的 key

  • MessageQueue:消息容器,优先级链表结构,内部消息按照触发时间进行排序,enqueueMessage() 方法添加消息,next() 方法取出消息

public final class MessageQueue {
    //链表头部
    Message mMessages;
    
    //添加消息到链表中
    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {
            ...
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                //消息需要插入链表头部
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                ...
                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;
            }
            ...
        }
        return true;
    }
    
    //取出消息
    Message next() {
        ...
        for (;;) {
            ...

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                //当链表头部为同步消息屏障时,prevMsg将被赋值
                Message prevMsg = null;
                Message msg = mMessages;
                //当消息的 target 为空时,表示这条消息是同步屏障消息,此时会优先查询链表中的异步消息,当没有异步消息时会阻塞
                if (msg != null && msg.target == null) {
                    // 查找链表中的异步消息
                    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 {
                    // 没有消息,进入阻塞状态
                    nextPollTimeoutMillis = -1;
                }
                ...
        }
    }
}
  • 同步消息屏障 消息是根据触发时间进行先后排序的,它们保存在优先级链表中,依次从头部取出消息并处理,那么需要紧急处理的消息该怎么办?这个时候同步消息屏障就产生作用了。 postSyncBarrier() 方法添加同步消息屏障, removeSyncBarrier() 删除同步消息屏障。同步屏障消息其实就是 msg.target == null 的消息,添加了同步屏障消息之后会优先处理异步消息,执行效果如下

飞书20220114-103356.png

  • Handler
//sendXXXMessage 和 post 等方法最后都是调用 sendMessageAtTime 
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
    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(@NonNull MessageQueue queue, @NonNull Message msg,
        long uptimeMillis) {
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();
    //通常我们发的消息是同步消息
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}