編輯:Android 資訊
消息機制幾乎是每次 Android 面試都繞不開的考點。但學習它的意義遠不止於應對面試——在日常開發中,它扮演著舉足輕重的角色,真正理解其運作原理至關重要。下面就從最基礎的概念說起。
核心作用:
Looper 的構造方法是私有的,內部主要完成兩件事:創建一個 MessageQueue,以及記錄當前所屬的 Thread。
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
不能。一個線程只能對應一個 Looper,這由 ThreadLocal 來保證。若重複調用 Looper.prepare(),將拋出運行時異常。
private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { // 檢查是否已有 Looper 與當前線程關聯 throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
會。開啟 loop 後本質上是一個死循環,不斷從 MessageQueue 中取出並處理消息;不過它也存在退出機制——當隊列中沒有消息且收到退出信號時,循環便會結束。
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(); // might block if (msg == null) { // 沒有消息時退出循環 return; } // 略 msg.target.dispatchMessage(msg); }
不可以。prepareMainLooper 最終也是調用 prepare(),原因同第 2 點。
public static void prepareMainLooper() { prepare(false); // 創建 Looper synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
MainLooper 在啟動 Activity、創建 ActivityThread(注意它並不是一個 Thread)時被創建,因此無法重複創建。
public static void main(String[] args) { // 略 Process.setArgV0("<pre-initialized>"); 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 對應一個線程,並包含一個 MessageQueue。當我們創建 Handler 時,會先從當前線程取出對應的 Looper,再從 Looper 中取得 MessageQueue。
// 1、自動獲取 public Handler(Callback callback, boolean async) { // 略 mLooper = Looper.myLooper(); // 取出當前線程中的 Looper if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; // 取出 MessageQueue mCallback = callback; mAsynchronous = async; } // 2、傳入一個 Looper public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
數據結構為單項鏈表。
核心作用:
通過一個全局的消息池(鏈表結構)來實現複用。
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(); }
在 Android 中傳遞對象需要實現 Serializable 或 Parcelable 接口,而 Message 實現了 Parcelable。
public final class Message implements Parcelable { // 略 }
在消息傳遞機制中,Handler 扮演著「快遞員」的角色,那麼它又是如何與「貨物」——Message 建立聯繫的呢?其實 Message 有一個類型為 Handler 的成員變量 target。
/*package*/ Runnable callback; public int arg1; public int arg2; public Object obj; /*package*/ Handler target; // 關鍵點
當我們通過 Handler 發送一個 Message 時,最終都會將 target 賦值為 this,即當前這個 Handler。
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()。
public final Message obtainMessage(){ return Message.obtain(this); }
通過一系列包含關係,Looper、Handler、Message、MessageQueue 彼此關聯,形成一個閉環,從而開啟消息循環。

在學習這部分知識的過程中,由於能力有限,仍有一些問題值得進一步探討。若你對下面的問題有更好的理解,歡迎交流指正。
1、Message 中的 sPool 在哪裡初始化?為什麼 Message.obtain() 不會拋異常?
2、ActivityThread 並不是線程,為什麼能創建 Looper?Main Thread 又是何時創建的?
3、為什麼序列化後的對象就能傳遞?是否與 Binder 有關?
4、MessageQueue 對應的是 NativeMessageQueue,其底層實現值得進一步學習。
5、Looper.loop() 會退出嗎?退出的時機是什麼?若會退出,主線程是否也會隨之退出?
Android Tab 類型介面實現方式總結
Tab 類型介面是 Android App 中非常常見的導覽方式。它讓使用者能在多個功能頁之間快速切換。本文整理五種常見實作方式,包含 TabActivity、ViewP
每個 Android 開發者都該認識的 Kotlin:特性、優勢與上手
Android 開發者在語言層面長期受限:官方支持停留在 Java 6(語言本身在 Java 7 上做過少量改進),結果是大量樣板代碼與脆弱易錯的表達方式,可讀性與可維護
Android 注解入門:從 Override 到編譯期處理
注解是 Android 開發中常見的工具,最典型的例子就是 @Override。它會在編譯期檢查方法是否正確重寫父類,也能提升程式碼可讀性。注解的價值除了標記用途,注解還
用 PHP 打造 Android 應用程式的完整教學
Google 的 Android 作業系統是開源專案,與對上架審核嚴格把關的 Apple App Store 相比,Android 平台開放得多。這種開放甚至延伸到了語言