本文章基于AndroidAPI28,主要分析messageQueue 單鏈表實現(xiàn)的意義和用法乔外、messageQueue.next() 以及 Looper.loop()方法
1. 相關調用圖
ps:不會畫圖簡單看一下吧
2. 相關方法介紹
1.1 Handler
使用方式不具體介紹了J偾础(簡單說一下)
內部類重寫handMessage方法芹枷,調用handler.post(sendMessage 等其他方法),最終都會調用sendMessageAtTime() 方法
// uptimeMillis = 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);
}
mQueue 在構造函數(shù)中注入贝咙,默認構造使用主線程Looper.mQueue (自行閱讀構造函數(shù)源碼)
1.2 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.
<p>You can retrieve the MessageQueue for the current thread with
{@link Looper#myQueue() Looper.myQueue()}.
低級類,保存由Looper調度的消息列表拂募。消息不是直接添加到MessageQueue庭猩,而是通過與Looper關聯(lián)的Handler對象添加。 您可以使用Looper#myQueue() 檢索當前線程的MessageQueue陈症。
1.2.1 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) {
...
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 {
//插入隊列中間蔼水。通常,除非隊列的開頭有障礙并且消息是隊列中最早的異步消息录肯,否則我們不必喚醒事件隊列趴腋。
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
// 按照when從小到大的順序將msg 插入 鏈表實現(xiàn)的隊列中;
for (;;) {
)
prev = p;
p = p.next;
// 依次移動指針论咏,直到找到p==null(隊列尾部 )或者 msg.when<p.when(要插入的msg的when比p指針的小)
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;
}
需要注意的幾點:
- nativeWake可以喚醒由nativePollOnce方法引起的阻塞
- msg.when = SystemClock.uptimeMillis() + delayMillis(類似postDelay等方法中傳入的delay參數(shù))
- nativePollOnce 可以阻塞Android 主線程而且不會出現(xiàn)ANR盐固,具體分析看這里
1.2.2 MessageQueue#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;
}
// 這里是IdleHandler 取出Msg的邏輯蚣抗,詳見下一節(jié)
// 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;
}
}
1.2.3 IdleHandler 簡單使用、分析
使用:Looper.myLoop().getQueue().addIdleHandler(),可以用來做一些預加載的操作
public void addIdleHandler(@NonNull IdleHandler handler) {
synchronized (this) {
mIdleHandlers.add(handler);
}
}
Q : next()方法中IdleHandler是怎么被取出然后執(zhí)行的?
A : 在MessageQueue#next方法死循環(huán)中使用pendingIdleHandlerCount(local variable)控制執(zhí)行次數(shù)鱼蝉,可以避免加鎖操作哼御!
// 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;
1.3 Looper
1.3.1 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;
for (;;) {
// 調用next方法 取出
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
......
try {
// 回調handler的dispatchMessage方法佳鳖,形成一個閉環(huán)
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
// 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();
}
}