1. 消息队列的工作原理
消息队列在
Android
中指的是MessageQueue
,MessageQueue
主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作,插入
和读取
对应的方法分别为enqueueMessage
和next
,其中enqueueMessage
的作用是往消息队列中插入一条消息,而next
的作用是从消息队列中取出一条消息并将其从消息队列中移除。尽管MessageQueue
叫消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息列表,单列表在插入和删除上比较有优势。
MessageQueue的结构是一个单向链表,插入和删除比较有优势。
-
enqueueMessage
的源码如下所示:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) { // 此处的target就是Handler
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
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() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, 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 (DEBUG) Log.v(TAG, "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(TAG, "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
方法会返回这条消息并将其从单链表中移除。
2. Looper的工作原理
Looper
在Android
的消息机制中扮演着消息循环的角色,具体来说,就是它会不停地从MessageQueue
中查看是否有新消息,如果有新消息就会立即处理,否则就一直阻塞在那里。首先看一下它的构造方法,在构造方法中它会创建一个MessageQueue
,即消息队列,然后将当前线程的对象保存起来。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Handler
的工作需要Looper
,没有Looper
的线程就会报错,那么如何为一个线程创建Looper
呢?其实很简单,通过Looper.prepare()
即可为当前线程创建一个Looper
,接着通过Looper.loop()
来开启消息循环。
new Thread("Thread#2") {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}.start();
Looper
除了prepare()
方法外,还提供了prepareMainLooper()
方法,这个方法主要是给主线程也就是ActivityThread
创建Looper
使用的,其本质也是通过prepare()
方法来实现的。由于主线程的Looper
比较特殊,所以Looper
提供了一个getMainLooper()
方法,通过它可以在任何地方获取到主线程的Looper
。
Looper
也是可以退出的,Looper
提供了quit
和quitSafely
来退出一个Looper
,两者的区别是:quit
会直接退出Looper
,而quitSafely
只是设定一个退出标记,然后把消息队列中的已有消息处理完毕后才安全地退出。Looper
退出后,通过Handler
发送的消息会失败,这个时候Handler
的send
方法会返回false
。在子线程中,如果手动为其创建了Looper
,那么在所有的事情完成以后应该调用quit
方法来终止消息循环,否则这个子线程就会一直处于等待的状态,而如果退出Looper
以后,这个线程就会立刻终止,因此建议不需要的时候终止Looper。
Looper
最重要的一个方法是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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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.recycleUnchecked();
}
}
Looper
的loop
方法的工作过程也比较好理解,loop
方法是一个死循环,唯一跳出循环的方式是MessageQueue
的next
方法返回了null
。当Looper
的quit
方法被调用时,Looper
将会调用MessageQueue
的quit
或者quitSafely
方法来通知消息队列退出,当消息队列被标记为退出状态时,它的next
方法就会返回null
。也就是说,Looper
必须退出,否则loop
方法就会无限循环下去。loop
方法会调用MessageQueue
的next
方法next
方法来获取新消息,而next
是一个阻塞操作,当没有消息时,next
方法会一直阻塞在那里,这也导致loop
方法一直阻塞在那里。如果MessageQueue
的next
方法返回了新消息,Looper
就会处理这条消息:msg.target.dispatchMessage(msg)
,这里的msg.target
是发送这条消息的Handler
对象,这样Handler
发送的消息最终又交给它的dispatchMessage
方法来处理了。但是这里不同的是Handler
的dispatchMessage
方法是在创建Handler
时所使用的Looper
中执行的,这样就成功地将代码逻辑切换到指定的线程中去执行了。