- 目錄
- Handler、Looper、MessageQueue源碼解析——Handler
- Handler、Looper、MessageQueue源碼解析——Looper
- Handler、Looper、MessageQueue源碼解析——ThreadLocal
- Handler、Looper、MessageQueue源碼解析——MessageQueue
MessageQueue
/**
* Low-level class holding the list of messages to be dispatched by a
* {@link Looper}. Messages are not added directly to a MessageQueue,
* but rather through {@link Handler} objects associated with the Looper.
* You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
*/
Handler時用來發送消息的,調用sendMessageAtTime(),在調用MessageQueue的enqueueMessage(msg, uptimeMillis)方法,把消息插入到MessageQueue中。我們首先來看一下MessageQueue的enqueueMessage方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
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;
}```
在Looper的loop()方法中,開啟了一個死循環,通過調用MessageQueue的next()方法,不斷的取出消息,再交給Handler去處理。
Message msg = queue.next();```
我們來看一下MessageQueue的next()方法:
Message next() {
//注釋1
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;
//注釋2
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());
}
//注釋3
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.
//注釋4
if (mQuitting) {
dispose();
return null;
}
}```
首先看注釋1:mPrt==0時返回一個null,mPrt在什么時候為空呢,注意到有一個dispose()方法:
private void dispose() {
if (mPtr != 0) {
nativeDestroy(mPtr);
mPtr = 0;
}
}```
dispose()方法在哪調用呢,注意到在注釋4處,當mQuitting==true時調用dispose()方法。那么mQuitting在哪賦值為true呢:
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}```
也就是上節我們說到調用Looper中的quit()獲得quitSafely()時會賦值為true,MessageQueue退出循環。
再看注釋3:Message是一個單向鏈表,next指向下一個Message。首先會先判斷當前時間與Message的時間對比:
//獲取從開機到現在的時間
final long now = SystemClock.uptimeMillis();
when = SystemClock.uptimeMillis()+uptimeMillis;```
如果message已經準備好,則返回一個Message對象,并把Message的next指針指向下一個message。
再看注釋2:什么時候message的target對象為空,在Handler發送Message時制定了target對象,當message的target對象為空時說明不是由Handler插入進來的,在MessageQueue的源碼中找到這樣一個方法;
private int postSyncBarrier(long when) {
// Enqueue a new sync barrier token.
// We don't need to wake the queue because the purpose of a barrier is to stall it.
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
if (prev != null) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}```
相當于設置一個消息屏障,如果遇到一個消息屏障,就會不停的循環找到一個異步消息,一般我們使用的都是同步消息,我們可以通過Message的setAsynchronous(true)方法指定為異步消息。
既然有開始循環,那么必定會有退出循環,我們調用Looper的quit()或者quitSafely()方法時實際調用的是MessageQueue的quit方法。quit()和quitSafely()方法的區別在Looper中已經提到了,分別調用了
removeAllMessagesLocked()和removeAllFutureMessagesLocked()方法,現在我們來看一下具體實現:
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}```
因為Message是一個單向鏈表,把所有的Message回收掉。
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}```
當p.when > now時,即又延時的消息全部清空,對于沒有延時的消息,通過一個死循環等待Handler處理完再回收。
我們注意到無論是Looper的loop()方法還是MessageQueue的next()方法,都是一個死循環,那么為什么不會造成阻塞或者對CPU有什么消耗上的影響?請參考知乎大神回答:[Android中為什么主線程不會因為Looper.loop()里的死循環卡死?](https://www.zhihu.com/question/34652589)