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

Android 消息處理機制源碼全解(一):Handler、Looper 與 MessageQueue 如何完成執行緒切換

編輯:關於 Android 程式設計

所謂 Android 消息機制,從開發者的視角看只有一個對外接口——Handler。透過 Handler,我們可以把一段任務丟到它所屬的執行緒去執行,最常見的用法就是更新 UI。

Android 的 UI 控件只能在主線程(UI 線程)操作,但我們通常在子線程或線程池裡做耗時、联网的工作。工作完成後要更新介面,比如關閉對話框、換掉按鈕文字,最直覺的做法就是建立一個 Handler,把更新邏輯寫在 handleMessage 裡,然後在子線程發送消息。

不過 Handler 並不是為這件事而生,它只是剛好非常適合。那麼它是怎麼做到「切換執行緒」的?為什麼 Handler 一定要在主線程建立?下面從源碼走一遍完整流程。

一、先認識五位主角

  • Handler:處理器,負責消息的發送與處理。開發時通常繼承它並改寫 handleMessage,依不同的 message 做不同的 UI 更新。
  • Message:消息本體,承載要傳遞的資料。
  • MessageQueue:消息隊列,以單鏈表按時序存放 Message,被 Looper 使用(一個 Looper 對應一個 MessageQueue)。
  • Looper:循環器,整個機制的核心。一條線程最多一個 Looper 且一一對應,它負責不停從 MessageQueue 取出消息,交給對應的 Handler 處理。
  • ThreadLocal:線程本地儲存,為每條線程保存各自獨立的資料。

二、消息循環總覽

先用最精簡的語言把流程串起來:

  1. Looper 透過 ThreadLocal 與線程綁定,每條線程可以有自己的 Looper,每個 Looper 自帶一個 MessageQueue。Looper 的 code 跑在自己所屬的線程上,不斷嘗試從隊列取消息;隊列為空時就阻塞等待。
  2. 我們在主線程建立了 Handler,它會抓取當前線程(主線程)的 Looper。也就是說,沒有 Looper 的線程建立不出 Handler。當我們(哪怕是在子線程裡)呼叫 Handler 發送消息,消息會被放進這個 Looper 的 MessageQueue。
  3. Looper 立刻取出這條新消息,呼叫發送方的 handleMessage。由於這個 Looper 跑在主線程,我們的 UI 更新邏輯就在主線程執行了——切換完成。

三、MessageQueue 與 Looper

1. MessageQueue:enqueueMessage

MessageQueue 只需要兩個核心操作:插入與讀取,對應 enqueueMessage 與 next。

final boolean enqueueMessage(Message msg, long when) {
    if (msg.isInUse()) {
        throw new AndroidRuntimeException(msg + " This message is already in use.");
    }
    if (msg.target == null) {
        throw new AndroidRuntimeException("Message must have a target.");
    }

    boolean needWake;
    synchronized (this) {
        if (mQuiting) {
            return false;
        }
        msg.when = when;
        Message p = mMessages;
        if (p == null || when == 0 || when < p.when) {
            // 成為新的鏈頭,若有阻塞需喚醒
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // 插入隊列中段
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p;
            prev.next = msg;
        }
    }
    if (needWake) {
        nativeWake(mPtr);
    }
    return true;
}

開頭兩段檢查擋掉了兩種非法狀態:消息正在使用中,以及消息沒有 target。target 就是發送它的 Handler,後續真正處理消息的也是它。之後就是標準的單鏈表有序插入,when 決定插入位置。

尾部的 needWake 與 nativeWake(mPtr) 牽涉到 native 層的阻塞喚醒機制(epoll),邏輯相當細緻,這裡先擱著,等整體框架講完再回頭看底層。

2. MessageQueue:next

final Message next() {
    int pendingIdleHandlerCount = -1;   // 空閒回調數量
    int nextPollTimeoutMillis = 0;      // 下次輪詢的等待時間

    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        nativePollOnce(mPtr, nextPollTimeoutMillis);

        synchronized (this) {
            try {
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                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;
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // 隊列已空,無限期等待
                    nextPollTimeoutMillis = -1;
                }
            } finally {
                if (pendingIdleHandlerCount >= 0) {
                    // 處理 IdleHandler
                }
            }
        }
    }
}

mMessages 是鏈表的頭,也就是下一個待處理的消息。next 本質上是一個阻塞方法:隊列為空時它會一直卡在循環裡;找到鏈頭消息後還要比對時間是否到齊;兩個條件都滿足才把消息摘除並回傳:

// Got a message.
mBlocked = false;
if (prevMsg != null) {
    prevMsg.next = msg.next;
} else {
    mMessages = msg.next;
}
msg.next = null;
msg.markInUse();
return msg;

這裡最關鍵的一句是 nativePollOnce(mPtr, nextPollTimeoutMillis)。它讓 Looper 在沒有消息時真正進入休眠,而不是空轉燒 CPU——這一點非常重要,否則主線程會把一個核心吃滿。開頭那兩個區域變數(pendingIdleHandlerCount 與 nextPollTimeoutMillis)也全是為了配合這個 native 呼叫,留待底層篇細說。

3. Looper:一個 Looper 一個 MessageQueue

// 成員變數之一
final MessageQueue mQueue;

private Looper() {
    mQueue = new MessageQueue();
    mRun = true;
    mThread = Thread.currentThread();
}

構造函數是私有的,每個 Looper 在建立時就擁有一個全新的 MessageQueue。

4. Looper.prepare:把 Looper 綁到當前線程

既然 Looper 與線程一對一,那它在何處初始化?前面說過,沒有 Looper 的線程建立不了 Handler。我們平常之所以沒感覺,是因為在主線程建立 Handler,而主線程預設就有一個主消息循環。子線程要自己開:

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();   // 為當前線程建立消息循環
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // 在這裡處理消息
            }
        };
        Looper.loop();      // 啟動消息循環
    }
}
private static final ThreadLocal sThreadLocal = new ThreadLocal();

public static final void prepare() {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper());
}

ThreadLocal 在這裡扮演「線程 → 專屬 Looper」的映射表。prepare 做兩件事:先檢查當前線程是否已有 Looper,有的話直接拋異常(這就是「一條線程只能有一個 Looper」的由來);沒有則建立並存入 ThreadLocal。

5. 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;

    for (;;) {
        Message msg = queue.next();     // 可能阻塞
        if (msg == null) {
            // 沒有消息代表消息隊列正在退出
            return;
        }
        msg.target.dispatchMessage(msg);
        msg.recycle();
    }
}

必須先記住一個前提:loop() 是跑在 Looper 所屬線程上的。主線程的 loop 跑在主線程,LooperThread 的 loop 跑在 LooperThread。

逐步拆解:

步驟一,取得當前線程的 Looper:

public static final Looper myLooper() {
    return (Looper) sThreadLocal.get();
}

步驟二,若為 null 表示沒呼叫過 prepare(),直接拋異常。

步驟三,進入無限循環,不斷向 MessageQueue 索取消息:

final MessageQueue queue = me.mQueue;
for (;;) {
    Message msg = queue.next();
    if (msg == null) {
        return;
    }
    msg.target.dispatchMessage(msg);
    msg.recycle();
}

當 Looper 呼叫 quit(),MessageQueue 隨之退出,next() 回傳 null,迴圈 return——這就是 Looper 的退出路徑。

拿到非 null 的 Message 後,呼叫的是 msg.target.dispatchMessage(msg)。target 是什麼?看 Message 的成員宣告:

Handler target;   // 發送並處理消息的 Handler

就是我們的 Handler。而這行 dispatchMessage 是在 loop 中呼叫的,也就是在 Looper 所屬的線程中執行。執行緒切換在這一句就已經完成了。

四、Handler 做了什麼

說了這麼多,Handler 反而是最單純的角色。消息的獲取與派發全是 Looper 在做,Handler 只是「發出」一個 Message——嚴格說也不是發出,只是往 Looper 的 MessageQueue 裡塞了一個物件。

1. 構造函數

public Handler() {
    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 = null;
}

三件事依序發生:取得當前線程的 Looper(沒有就拋異常,前面那句結論在此得到印證);拿到 Looper 的 MessageQueue 存為 mQueue,顯然是為了後續插消息;把 mCallback 初始化為 null。

2. sendMessage 系列

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    boolean sent = false;
    MessageQueue queue = mQueue;
    if (queue != null) {
        msg.target = this;                          // 1. target 指向自己
        sent = queue.enqueueMessage(msg, uptimeMillis);  // 2. 入隊
    } else {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
    }
    return sent;
}

所有 sendMessage 變體最終都匯流到 sendMessageAtTime。它做的事非常直白:把 msg.target 設為自己(這正好解釋了 enqueueMessage 開頭那個 target 檢查),然後呼叫 enqueueMessage 入隊。延遲消息也不過是把 uptimeMillis 往後推。

3. dispatchMessage:三級優先順序

public void dispatchMessage(Message msg) {
    // 1. Message 自帶 callback,優先交給它
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        // 2. Handler 自身的 callback
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        // 3. 兩者皆無,走我們改寫的 handleMessage
        handleMessage(msg);
    }
}

第一級:Message 上的 callback。

Runnable callback;   // 處理消息的回呼

它其實就是 post() 傳進來的 Runnable:

private static void handleCallback(Message message) {
    message.callback.run();
}

public final boolean post(Runnable r) {
    return sendMessageDelayed(getPostMessage(r), 0);
}

private final Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

所以 handler.post(new Runnable(){ ... }) 的本質,就是把 Runnable 包成 Message 的 callback 再走一次 sendMessage 流程。

第二級:Handler 的 Callback 介面。

public interface Callback {
    public boolean handleMessage(Message msg);
}

public Handler(Callback callback) {
    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;
}

這是繼承 Handler 之外的第二種寫法:不改寫 handleMessage,而是傳入一個實作了 Callback 的物件。回傳 true 表示消息已被消費,不再往下走。

第三級:改寫 handleMessage。前兩級都沒命中時,才輪到我們最熟悉的那個方法。

五、主線程的循環是誰開的

回到最初的問題:為什麼在主線程建立 Handler 不需要自己寫 Looper.prepare()?答案在主線程的入口:

public static void main(String[] args) {
    Looper.prepareMainLooper();
    // ...
    Looper.loop();
}
public static final void prepareMainLooper() {
    prepare();
    setMainLooper(myLooper());
}

private synchronized static void setMainLooper(Looper looper) {
    mMainLooper = looper;
}

prepareMainLooper 只是 prepare() 加一個「登記為主 Looper」的動作。ActivityThread.main 在方法末尾進入 Looper.loop() 之後就再也不返回——主線程的生命,就是這個無限迴圈的生命。

小結

把流程攤開來看,Handler 其實不是主角,真正撐起執行緒切換的是 Looper 與 MessageQueue:Looper 決定「在哪條線程執行」,MessageQueue 決定「什麼時候執行」,Handler 只負責標記「誰來執行」(msg.target)。

這篇先把整體框架與各類別的關鍵函數梳理清楚。MessageQueue 那兩個 native 方法(nativePollOnce、nativeWake)背後还有一層 C++ 的 epoll 阻塞與管道喚醒機制,留待下一篇深入。但至少現在我們已經明白:Handler 的實現,比它的用法複雜太多了。

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