本文是在读《Android开发艺术探索》这本书中关于“Android的消息机制”时所作记录,以便加深对Android的消息机制的理解。
一、概述
Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue 和 Looper的支撑。MessageQueue以队列的形式对外提供插入和删除的工作,虽然叫Queue,但实际上它是采用单链表的数据结构来存储消息列表;Looper 可以理解为消息循环,Looper会以无限循环的形式去查找是否有新消息,如果有的话就处理,如果没有就一直等待。
我们知道Handler 创建的时候会采用当前线程的Looper来构建消息循环系统,那么Handler内部是如何获取到当前线程的Looper呢? 这就需要使用ThreadLocal了。ThreadLocal不是线程,它的作用是可以在不同线程中互不干扰地存储并提供数据。有关ThreadLocal的知识请参考:ThreadLocal基本原理及应用
需要注意的是,线程默认是没有Looper的,如果需要使用Handler就必须为线程创建Looper。可能你会有这样的疑问:在开发过程中,经常在主线程中创建Handler用于处理耗时操作并更新UI,也没有创建Looper而是直接使用Handler的啊? 这是因为我们常提到的主线程,也叫UI线程,它就是ActivityThread。 ActivityThread在被创建的时候,会初始化Looper, 所以才不用我们创建了,直接默认使用Handler.
Handler的主要作用是将一个任务切换到某个指定的线程中去执行。那么Android为什么要提供在某个具体的线程中去执行任务这种功能呢?这是因为Android规定访问UI只能在主线程中进行,如果在子线程中访问UI,程序会抛异常。
二、消息队列的工作原理
MessageQueue主要包含了两个操作:插入和读取;读取操作本身会伴随着删除。插入和读取对应的方法分别为enqueueMessage 和 next , 其中enqueueMessage的作用是往消息队列中插入一条消息,而next的作用是从消息队列中取出一条消息并将其从消息队列中删除。下面我们来看看源码。
boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
synchronized (this) {
if (mQuitting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}
msg.when = when;
Message p = mMessages;
boolean needWake;
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 {
// 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;