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

深入 Handler 消息機制(一):Looper、MessageQueue 與 Message 的關係

編輯:關於 Android 程式設計

上一篇我們一路追蹤 Handler.sendMessage() 的呼叫鏈,最終會落到 sendMessageAtTime() 這個方法上:

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);
}

短短幾行 code 裡就浮現出兩個關鍵角色:MessageQueue 與 enqueueMessage()。這意味著 Handler 的背後一定存在一個消息隊列,負責存放我們送進去的種種 Message 物件。接下來,就沿著這條線把藏在 Handler 之後的機制一層層掀開。

從 Handler 的建構談起

我們平時最常見的寫法是直接 new 一個匿名 Handler:

private Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_ID_1:
                Log.v("Test", "Toast called from Handler.sendMessage()");
                break;
            case MSG_ID_2:
                String str = (String) msg.obj;
                Log.v("Test", str);
                break;
        }
    }
};

那麼它的建構函數裡究竟做了什麼?原始碼提供了一整排重載版本:

public Handler() { this(null, false); }
public Handler(Callback callback) { this(callback, false); }
public Handler(Looper looper) { this(looper, null, false); }
public Handler(Looper looper, Callback callback) { this(looper, callback, false); }
public Handler(boolean async) { this(null, async); }

public Handler(Callback callback, boolean async) {
    // ... 省略 leak 檢查 ...
    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;
}

public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

看起來版本繁多,但真正做事的其實只有下面這兩個,其餘都只是把參數轉手傳進來:

public Handler(Callback callback, boolean async) { ... }
public Handler(Looper looper, Callback callback, boolean async) { ... }

兩者的差別只在「有沒有傳入 Looper」。而 Looper 是一個與線程綁定的物件——所謂線程相關變數,就是不會在線程之間共享、只在所屬線程內有效的那類物件。

建構函數裡有兩行特別值得記住:mLooper = Looper.myLooper() 取得當前線程的 Looper,接著 mQueue = mLooper.mQueue 把 Looper 內部的 MessageQueue 接手過來。若當前線程沒有 Looper,就會直接拋出 Can't create handler inside thread that has not called Looper.prepare() 這個我們偶爾會撞到的錯誤。

Looper 究竟負責什麼

就我個人的理解,Looper 可以看作 MessageQueue 的外殼封裝,它主要做兩件事。

1. 建立 Looper,同時初始化 MessageQueue

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

MessageQueue 正是在 Looper 被 new 出來的那一刻完成初始化的。值得注意的是這個建構函數是 private 的,能觸發它的只有 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));
}

Looper 建立好之後會被放進 sThreadLocal。ThreadLocal 就是線程局部變數,這也解釋了 Looper 的一個核心特性:每一條線程只能擁有一個 Looper 物件,重複呼叫 prepare() 就會拿到上面那個「Only one Looper may be created per thread」的例外。

2. 透過 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(); // might block
        if (msg == null) {
            // 拿到 null 代表消息隊列正在關閉
            return;
        }
        msg.target.dispatchMessage(msg);
        msg.recycle();
    }
}

邏輯非常直白:在一個無盡迴圈裡,從 MessageQueue 取出一個 Message,交給 msg.target.dispatchMessage(msg) 去處理,處理完再回收。這裡的 msg.target 就是最初把消息塞進隊列的那個 Handler,消息繞了一圈又回到自己身上。

順道聊聊 recycle():Message 的複用池

dispatchMessage 先放一邊,我們看看 recycle() 到底忙了些什麼:

private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

public void recycle() {
    clearForRecycle();
    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

Message 自己帶了一個 next 欄位,於是眾多 Message 可以像鏈表一樣串起來,形成名為 sPool 的靜態消息池,池子上限是 50 個。

呼叫 recycle() 時,會先把物件狀態清乾淨(clearForRecycle),再把當前 Message 掛到 sPool 的頭部;而呼叫 Message.obtain() 時,則是反過來從 sPool 摘一個空物件出來重用,只有池子裡沒貨了才真的 new 一個新的。

看到這裡,上一篇為什麼建議大家優先使用 Message.obtain() 而不是 new Message(),答案就很清楚了——反覆建立又丟棄大量 Message 會製造不必要的 GC 壓力,重用池中的物件在記憶體受限的行動裝置上是實打實的優化。

小結:在新線程裡使用 Handler

把前面的線索串起來,可以得出一個結論:任何線程若想建立 Handler,這條線程就必須先有 Looper;而 Looper 內部又封裝了一個 MessageQueue 來管理 Message。所以自訂線程要玩 Handler,得先自己把台階搭好:

class LooperThread extends Thread {
    public Handler mHandler;
    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // 在這裡處理收到的消息
            }
        };
        Looper.loop();
    }
}

實際跑一次會更直觀:

public class MainActivity extends ActionBarActivity {
    private static final int MSG_ID_1 = 1;
    private static final int MSG_ID_2 = 2;

    class LooperThread extends Thread {
        public Handler mHandler;
        public void run() {
            Looper.prepare();
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    Log.v("Test", "Id of LooperThread : " + Thread.currentThread().getId());
                    switch (msg.what) {
                        case MSG_ID_1:
                            Log.v("Test", "Toast called from Handler.sendMessage()");
                            break;
                        case MSG_ID_2:
                            Log.v("Test", (String) msg.obj);
                            break;
                    }
                }
            };
            Looper.loop();
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("Test", "Id of MainThread : " + Thread.currentThread().getId());

        LooperThread looperThread = new LooperThread();
        looperThread.start();
        while (looperThread.mHandler == null) { }

        Message message = Message.obtain();
        message.what = MSG_ID_1;
        looperThread.mHandler.sendMessage(message);

        Message msg2 = Message.obtain();
        msg2.obj = "I'm String from Message 2";
        msg2.what = MSG_ID_2;
        looperThread.mHandler.sendMessage(msg2);
    }
}

LogCat 的輸出印證了整套機制:

V/Test: Id of MainThread : 1
V/Test: Id of LooperThread : 68421
V/Test: Toast called from Handler.sendMessage()
V/Test: Id of LooperThread : 68421
V/Test: I'm String from Message 2

主線程負責 sendMessage,工作線程負責 handleMessage,兩邊涇渭分明。

這裡自然會浮現一個疑問:為什麼我們在主線程 new 一個 Handler 從來不用自己呼叫 Looper.prepare() 和 Looper.loop()?答案是——需要,只不過這一步 Android 系統在啟動主線程時已經替我們做完了,所以開發者不必再手動初始化。

這一篇我們把線程、Looper、Handler、MessageQueue 與 Message 之間的關係梳理了一遍,重點在於認識 Looper 這個「每線程唯一」的消息引擎。下一篇再往裡走,看看消息入隊之後是怎麼被排隊與取出的。

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