本文是在读《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;
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;
}
从enqueueMessage的实现来看,主要就是单链表的插入操作。下面看一下next方法的实现。
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// We can assume mPtr != 0 because the loop is obviously still running.
// The looper will not call this method after the loop quits.
nativePollOnce(mPtr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
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 (false) Log.v("MessageQueue", "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
可以看到next是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞,当有新消息到来,next方法就会返回这条消息并将其从单链表中移除。
三、Looper的工作原理
Looper在Android的消息机制中扮演着消息循环的角色,具体来说就是它会不停地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就会一直阻塞。首先看一下它的构造方法。
在构造方法中它会创建一个MessageQueue,然后将当前线程的对象保存起来。
Looper最重要的一个方法就是loop,只有调用了loop方法后,消息循环系统才能真正地起作用。看一下loop的源码。
public static void loop() {
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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycle();
}
}
loop方法是一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回null. 当Looper的quit方法被调用时,Looper就会调用MessageQueue的quit或者quiteSafety方法来通知消息队列退出,当消息队列被标记为退出状态时,它的next方法就会返回null,也就是说,Looper必须退出,否则loop方法就会一直无限循环下去。
loop方法会调用MessageQueue的next方法来获取新信息,而next是一个阻塞的操作,这也导致loop方法一直阻塞。
如果MessageQueue的next方法返回了新消息,Looper就会处理这条消息:msg.target.dispatchMessage(msg);
这里的msg.target是发送这条消息的Handler对象,这样Handler发送的消息最终又交给它的dispatchMessage方法来处理了。但是这里不同的是,Handler的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,这样就成功的将代码逻辑切换到指定的线程中去执行了。
四、Handler的工作原理
Handler 的工作主要包括消息的发送和接收过程。消息的发送可以通过post或者send一系列方法来实现,post最终其实调用的也是send方法。看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) {
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) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
从源码中可以看出,sendMessage最终调用了enqueueMessage方法,其实Handler发送消息的过程仅仅是向消息队列中插入一条消息。MessageQueue的next方法就会返回这条消息给Looper,Looper接收到消息就开始处理,最终消息由Looper交给Handler处理,Handler的dispatchMessage方法就会被调用,这时Handler就进入了处理消息的阶段。下面看看dispatchMessage方法的源码。
从源码中可看出,Handler的处理过程如下:
首先,检测Message的callback是否为null,不为null就通过handleCallback来处理消息,Message的callback是一个Runnable对象,实际上就是post方法传递的Runnable参数。handleCallback的处理逻辑也很简单。
其次,检测mCallback是否为null,不为null就调用mCallback的handleMessage方法来处理消息。看一下Callback的定义。
Callback的意义是什么呢? 注释已经说明:可以用来创建一个Handler的实例但并不需要派生Handler子类。通过Callback可以采用如下方式创建Handler
Handler handler = new Handler(callback);
Handler 还有一个特殊的构造函数,那就是通过Looper来构造Handler,它的实现如下,通过这个方法可以实现一些特殊的功能。
下面看Handler的一个默认方法Handler(),这个方法调用了Handler(Callback callback, boolean async); 看源码。
很明显,如果当前线程没有looper的时候,就会抛出“Can't create handler inside thread that has not called Looper.prepare()”这个异常,这也解释了在没有Looper的子线程中创建Handler会产生异常的原因。