編輯:關於 Android 程式設計
Handler 是我們每天在用的元件,但它背後的 Looper 與 MessageQueue 究竟如何運作?本文從原始碼切入,把這條訊息迴圈的脈絡梳理清楚。
public class HandlerThread extends Thread {
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
}
run() 一開始就呼叫 Looper.prepare(),為當前執行緒準備一個 Looper:
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
這裡用 ThreadLocal 中的 sThreadLocal 來保證每個執行緒各自擁有唯一且獨立的 Looper 實例——第二次呼叫就會直接丟出例外。準備好之後,HandlerThread 的 run() 便進入 Looper.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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // 沒有訊息時會在這裡阻塞
if (msg == null) {
// 拿到 null 代表訊息佇列正在關閉
return;
}
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);
}
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();
}
}
這是一個死迴圈,每一輪都從 MessageQueue 取出一個 Message 並交給目標 Handler 執行 dispatchMessage。至於 Binder.clearCallingIdentity(),作用應該是清掉遠端呼叫者的身分標記——因為跨程序 IPC 過來的執行緒未必具備本地進程的權限,清除身分之後,當前執行緒才能以本地進程的身分執行需要權限的操作。迴圈尾端再次比對身分是否被訊息處理過程悄悄改掉,就是一個防呆機制。
Message next() {
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1;
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// 遇到同步屏障,改找下一則非同步訊息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// 下一則訊息還沒到時間,設定逾時等待
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
return msg;
}
} else {
// 佇列已經沒有訊息了
nextPollTimeoutMillis = -1;
}
if (mQuitting) {
dispose();
return null;
}
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null;
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
nativePollOnce(ptr, nextPollTimeoutMillis) 會透過 JNI 做一次 poll。如果目前佇列裡沒有可處理的訊息(只剩下尚未到時間的定時訊息),這個方法就會一直卡在原生層,直到有新訊息進來或逾時到達才返回——這正是 Android 中「空閒時不佔用 CPU」的關鍵所在。
迴圈尾端還牽涉到一個觀念:IdleHandler。當佇列裡沒有任何可處理的訊息時,註冊過的 IdleHandler 會被回呼,也就是說 IdleHandler 被觸發,就代表此刻訊息佇列處於空閒狀態。若要使用,可以透過 MessageQueue 的 addIdleHandler 方法註冊。實務上常見的用法是拿來做低優先權的初始化工作,或在上一次 UI 繪製完成後才執行某些收尾動畫。
一個執行緒要跑起訊息迴圈,具備三個要素即可:Looper.prepare() 建立 Looper 並綁上 MessageQueue、建立 Handler 並指定要收訊息的 Looper、最後呼叫 Looper.loop() 進入迴圈。主執行緒在 ActivityThread 中就已經完成這些步驟,所以在 Activity 裡直接 new Handler() 不需要再呼叫 prepare()。反過來說,若在自行建立的子執行緒中少了 prepare(),Handler 便無處依附,這也是初學者最常踩的坑。
Android Spinner 用法解析
Spinner 基本概念 Spinner 是下拉式清單控制項,常用來讓使用者從一組選項中做選擇。 版面配置 <Spinner android:id=@+id/Spi
Android DialogFragment 對話框使用詳解
寫在前面 從事 Android 開發至今,一提到對話框,我就會想起 AlertDialog 或 PopupWindow,我在上一篇部落格中也整理過這兩種對話框的使用大全。
自製 Android PullToRefresh:下拉刷新、上拉加載,並可擴充 ScrollView、ListView、GridView
找了一圈開源方案,包含 GitHub 上頗有名氣的 Android-PullToRefresh,總覺得不太合手,最後決定自己寫一個,過程中自然也借鑑了一些前人的思路。核心
Android M Call 通話架構與狀態上報分析
Call 相關目錄與框架 Android M 的 Call 功能涉及 Dialer、InCallUI、Telecomm、Telephony 與 vendor 的 IMS