Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 消息機制重點整理:Looper、Handler、Message 與 MessageQueue

編輯:關於 Android 程式設計

Android 的消息機制幾乎是面試必考,但更值得學的理由是它在實際開發中無處不在——非同步回調、線程通訊、延遲任務,背後都是這套東西。本文用問答形式把關鍵點逐一拆開。

一、Looper

職責:把消息送進 MessageQueue,並且不斷從中取出消息交給對應的 Handler 處理。

Q1:Looper 可以直接 new 嗎?

不行,它的建構方法是私有的。建構時做兩件事:建立一個 MessageQueue,並記錄當前線程。

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

Q2:一個線程能有多個 Looper 嗎?

不能。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));
}

Q3:Looper 是無限循環,會不會卡住主線程?

確實是死循環,但當 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);
    }
}

Q4:能再次呼叫 prepareMainLooper 嗎?

不行。它內部同樣呼叫 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();
    }
}

Q5:主 Looper 什麼時候建立?

在應用啟動時,由 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 在正常情況下永遠不會執行。

二、Handler

職責:發送消息到 MessageQueue,並在目標線程處理消息。

Q1:Handler 如何與 Looper、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。

三、Message

底層是單向鏈表結構,用來串起複用池中的閒置物件。

職責:作為跨線程傳遞資料的載體。

Q1:Message 如何複用?

從一個全局的消息池(鏈表)中取,取完若池空才 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 壓力。

Q2:Message 為什麼能在進程間傳遞?

因為它實作了 Parcelable:

public final class Message implements Parcelable {
    // ...
}

Android 中要在 Binder 通道上傳物件,只有兩條路:Serializable 或 Parcelable。前者走 Java 序列化機制、效率較低且產生大量臨時物件;後者是 Android 專為效能設計的二維碼式序列化方案,內存拷貝次數更少。

Q3:Message 如何找到自己的 Handler?

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 消息機制基本上就沒有盲區了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved