編輯:關於 Android 程式設計
Android 的消息機制幾乎是面試必考,但更值得學的理由是它在實際開發中無處不在——非同步回調、線程通訊、延遲任務,背後都是這套東西。本文用問答形式把關鍵點逐一拆開。
職責:把消息送進 MessageQueue,並且不斷從中取出消息交給對應的 Handler 處理。
不行,它的建構方法是私有的。建構時做兩件事:建立一個 MessageQueue,並記錄當前線程。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
不能。Looper 透過 ThreadLocal 儲存,保證每個線程最多一個。重複呼叫 prepare() 會直接拋異常:
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));
}
確實是死循環,但當 MessageQueue 沒有可用消息時,queue.next() 會透過底層的 native 呼叫進入 epoll 等待,此時線程讓出 CPU 睡眠,而非忙等待。所以它不會白白消耗效能。另外,當佇列被標記為退出中,next() 會回傳 null,循環随之結束:
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 (;;) {
Message msg = queue.next(); // 無消息時在此阻塞
if (msg == null) {
// 佇列正在退出
return;
}
msg.target.dispatchMessage(msg);
}
}
不行。它內部同樣呼叫 prepare(false),並且多了一道主 Looper 是否已存在的檢查:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
在應用啟動時,由 ActivityThread.main() 建立。注意 ActivityThread 並不是一個 Thread 類,它只是一個管理應用進程生命週期的類,跑在主線程上:
public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
這也解釋了為什麼主 Looper 只能準備一次,以及為什麼 Looper.loop() 之後那行 throw 在正常情況下永遠不會執行。
職責:發送消息到 MessageQueue,並在目標線程處理消息。
建構時,若沒有顯式傳入 Looper,就抓當前線程的 Looper,再從中取出 MessageQueue:
// 方式一:自動抓取當前線程的 Looper
public Handler(Callback callback, boolean async) {
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;
}
// 方式二:顯式指定 Looper
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
這兩段程式也解釋了兩個常見現象:在裸線程 new Handler 會崩潰;而 new Handler(Looper.getMainLooper()) 可以在任意線程建立一個「往主線程投遞」的 Handler。
底層是單向鏈表結構,用來串起複用池中的閒置物件。
職責:作為跨線程傳遞資料的載體。
從一個全局的消息池(鏈表)中取,取完若池空才 new:
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // 清除 in-use 標記
sPoolSize--;
return m;
}
}
return new Message();
}
這也是為什麼官方建議用 Message.obtain() 或 Handler.obtainMessage() 而不是直接 new——高頻場景下能顯著減少 GC 壓力。
因為它實作了 Parcelable:
public final class Message implements Parcelable {
// ...
}
Android 中要在 Binder 通道上傳物件,只有兩條路:Serializable 或 Parcelable。前者走 Java 序列化機制、效率較低且產生大量臨時物件;後者是 Android 專為效能設計的二維碼式序列化方案,內存拷貝次數更少。
Message 有一個型別為 Handler 的成員變數 target:
/*package*/ Runnable callback; public int arg1; public int arg2; public Object obj; /*package*/ Handler target; // 關鍵
呼叫 Handler 的 send 系列方法時,最終都會在 enqueueMessage 裡為它賦值:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
透過 Message.obtain() 取得的複用物件也會被賦值,而 Handler.obtainMessage() 本質上就是 Message.obtain(this):
public final Message obtainMessage() {
return Message.obtain(this);
}
透過層層包含關係,四者形成一個閉環:

Thread 透過 ThreadLocal 持有唯一的 Looper;Looper 持有一個 MessageQueue;Handler 在建構時綁定 Looper 並取得其 Queue;Message 透過 target 記住要交給哪個 Handler。發送時消息入隊,Looper 循環取出後呼叫 msg.target.dispatchMessage(msg),回到最初那個 Handler 的 handleMessage。
整理過程中難免會留下一些需要更深入原始碼才能回答的問題,列在這裡作為後續閱讀的線索:
1. Message 裡的 sPool 在哪裡初始化?為什麼 obtain() 在多線程下不會出問題?(線索:sPoolSync 的鎖粒度,以及 recycleUnchecked 的歸還邏輯。)
2. ActivityThread 並不是 Thread,它憑什麼能建立 Looper?真正的 Main Thread 是哪一刻誕生的?(線索:fork 之後的 specializeApplication 流程。)
3. 序列化過的物件為什麼就能跨進程傳遞?這與 Binder 的 Parcel 傳輸有何關係?
4. MessageQueue 在 Java 層之下對應 NativeMessageQueue 與 Looper.cpp,next() 的阻塞究竟是怎麼實現的?(線索:epoll_wait 與管道 fd 的雙向喚醒。)
5. Looper.loop() 到底會不會退出?退出時機是什麼?主線程的 loop 若退出意味著什麼?(線索:quit 只對子線程的 Looper 生效,主 Looper 的 quitAllowed 為 false。)
把這五個問題追完,Android 消息機制基本上就沒有盲區了。
仿美團外賣點餐:兩個 ListView 聯動效果實作
點開外賣 App,左側是分類菜單,右側是對應的菜品列表,滑動任一側另一側同步反應——這就是典型的雙列表聯動。本文示範如何用兩個 ListView 搭配 setSelect
Android 入門:Menu 功能菜單的設計與事件響應實例
本文示範 Android 編程中的 Menu 功能菜單。程序裡定義了兩個菜單子項,一個是「關於」,一個是「退出」:點擊「關於」時彈出一個 Toast 提示,點擊「退出」時
Android sdcard 讀寫權限問題排查
在 Android 開發中,涉及外部存儲的讀寫操作經常會遇到權限問題。即使已在 AndroidManifest.xml 中聲明相關權限,運行時仍可能提示無法訪問 sdca
JNI 與 NDK 開發入門整理
JNI 是 Java 與原生程式碼溝通的橋樑,NDK 則讓 Android 開發者能編譯 C 或 C++ 程式碼,產出 so 動態連結庫。常見用途包括效能關鍵模組、加解密