編輯:關於 Android 程式設計
本文以 4.4.2_r1 版本的原始碼為基礎。Handler 與 Looper 是thread在 Android 中實現訊息循環的兩根支柱,另外兩個關鍵角色是 Message 與 MessageQueue。這四個類別合作,才讓一個原本的普通線程具備「接收並處理訊息」的能力。
Looper 類別的註解裡附了一段經典範例,正好是理解整個機制的最佳入口:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
這段程式示範了如何把一個普通線程「升級」為 Looper 線程。我們就從 Looper.prepare() 開始看。
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));
}
第 13 行拋出的異常訊息說得很明白:每個線程只允許擁有一個 Looper。判斷依據是 ThreadLocal,它保證每個線程各自持有獨立的 Looper 副本。第一次呼叫時會走到最後一行,建立 Looper 實例:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
建構子做了兩件事:建立一個 MessageQueue 並與自己綁定,以及抓取當前線程。於是 Looper 就同時綁上了「一個線程」與「一個訊息佇列」。
public static Looper myLooper() {
return sThreadLocal.get();
}
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
myLooper() 取回屬於當前線程的 Looper,getMainLooper() 則取回應用主線程的 Looper。後者由 prepareMainLooper() 賦值:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
註解特別提醒開發者「不該自己呼叫這個方法」。合理推測,它是在應用啟動時由框架代為呼叫的;由於 sMainLooper 是 static 欄位,屬於整個應用,重複呼叫自然就會拋出例外。
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass())
&& (klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: "
+ klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
關鍵在最後幾行:Handler 透過 Looper.myLooper() 取得本線程的 Looper,若之前沒呼叫過 prepare() 就會拿到 null 並拋出例外。這也解釋了一個常見疑問——為什麼在主線程寫 Handler 從來不用呼叫 prepare()?因為主線程預設已經綁好 Looper 了。取得 Looper 之後,Handler 直接把它的 mQueue 拿來用,兩者的關係就此建立。
另外還有一個可以指定 Looper 的建構子:
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
這個版本允許你把同一個 Looper 傳給多個 Handler。於是問題來了:多個 Handler 共用一個佇列時,訊息究竟由誰處理?答案藏在發送流程裡。
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);
}
注意 msg.target = this; 這一行。每個 Message 都有 Handler target 欄位,在進入佇列之前會被設為「送出它的那個 Handler」。這就是多 Handler 共用佇列時的答案:訊息由發送它的 Handler 自己處理。
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(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
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.recycle();
}
}
這裡有兩個容易誤讀的地方。第一,queue.next() 的註解寫著 might block——它可能阻塞。若以為「佇列沒訊息就會回傳 null 然後結束」,那就完全錯了;回傳 null 代表整個佇列進入退出狀態,是終止訊息機制的唯一訊號。第二,真正把訊息交出去的只有一行:msg.target.dispatchMessage(msg),而 target 正是稍早被寫入的 Handler 自己。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
public void handleMessage(Message msg) {
}
派遣順序是:先處理 Message 上的 Runnable callback,再來是 Handler 建構時傳入的 Callback 介面,最後才落到 handleMessage()。而 handleMessage() 在基類裡是空實作,註解也直說「子類別必須實作這個方法來接收訊息」——這正是我們在範例中覆寫它的原因。
1. 線程呼叫 Looper.prepare(),建立 Looper 並綁上 MessageQueue。
2. 建立 Handler,取得該 Looper 的佇列作為自己的 mQueue。
3. 呼叫 Looper.loop() 進入無限迴圈,阻塞等待訊息。
4. 任意線程透過 Handler 送出 Message,Message 的 target 被設為該 Handler 後進入佇列。
5. loop 取出訊息,交給 msg.target.dispatchMessage(),最終回到發送者所屬線程的 handleMessage()。
理解這條鏈路之後,像是「為什麼子線程不能直接更新 UI」這類問題,答案其實已經寫在原始碼裡了。
Android For JNI(二)——C 語言基礎:數據類型、輸入輸出、內存地址與內存修改器原理
Android For JNI(二)——C 語言基礎:數據類型、輸入輸出、內存地址與內存修改器原理 把 Hello World 跑通之後,就可以正式邁進 C 語言的大門
Android Native 層 Binder.transact() 呼叫 onTransact() 失敗分析
在 Native 層使用 Binder 進行跨進程溝通時,若 transact() 沒有如預期觸發對方的 onTransact(),通常不是單一 API 問題,而是 Bi
深入淺析 Android 消息機制
在 Android 中,線程內部或線程之間傳遞信息時經常會用到消息。這些看似基礎的東西,一旦我們摸透了背後的原理,就能更從容、更好地搭建系統架構,避免一些低級錯誤。 每個
Android 自定義狀態列通知實作
自定義通知的可控元件Android 通知列雖然空間有限,但仍是應用與使用者互動的重要位置。若需要更豐富的呈現方式,可以使用自定義通知版面。不過,通知的自定義版面基於 Re