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

Android 消息處理機制深度解析:Looper、Handler、MessageQueue 與 Message

編輯:關於 Android 程式設計

一、本質:一個線程的無限循環

消息處理機制的本質可以濃縮成一句話:一個線程開啟循環模式,持續監聽並依次處理其他線程交給它的任務。

更具體一點說,這個線程進入一個無限循環,不斷遍歷自己的消息列表:有消息就逐條取出處理,沒有消息就阻塞自己(等同 wait,主動讓出 CPU 給其他線程)。其他線程想讓它做事,就往它的消息隊列裡插入消息即可。這是一個典型的生產者—消費者模型。

二、四個角色各自解決了什麼問題

1. Looper:讓線程不要執行完就退出

線程本質是一段可執行程式碼,程式碼跑完線程生命週期就結束了。但主線程顯然不能這樣——App 啟動後執行幾行就自己退出,這完全不合理。 To avoid it,只能讓主線程的程式碼永遠執行不完,也就是插入一個死循環。

Looper 就是這個死循環的載體。在主線程中呼叫 Looper.prepare() 與 Looper.loop(),就把當前線程變成「Looper 線程」。loop() 內部是一個 while(true) 結構,主線程從此跳不出來;但主線程並非什麼都不做——所有事情都在這個循環裡做:它不斷等待其他線程發來的消息(Activity 啟動、生命週期回呼、UI 更新、控件事件……),一有消息就取出對應處理。Looper 的另一半職責,就是在循環中反覆從消息隊列取消息交給主線程執行。

2. MessageQueue:串行化的必需品

同一線程在同一時刻只能處理一件事,線程內部的程式碼不具備並發性,所以需要一個隊列來保存消息並約束處理順序。多個線程同時向 UI 線程投遞任務,UI 線程必須先把它們排進一個列表,再逐條取出處理。每個 Looper 線程都維護唯一一個這樣的隊列,且其中消息只能由所屬線程處理。

3. Handler:投遞與回調的統一入口

既然消息在主線程處理,其他線程怎麼把消息放進主線程的隊列?關鍵在於同進程內線程共享資源,任何變數都能跨線程讀寫,只要做好同步即可。也就是說,拿到 MessageQueue 的實例就能投遞。技術上確實可以在主線程寫 mLooper = Looper.myLooper(); mQueue = mLooper.mQueue; 拿到引用,但 Google 為了統一「投遞」與「回調」兩件事,另外封裝了 Handler:在主線程建構 Handler 時,它會自動持有主線程 MessageQueue 的引用,sendMessage 時就透過這個引用插入消息。

Handler 的第二個作用是統一處理回調。訊息入隊時,Message 會持有那個把它放進隊列的 Handler 的引用;主線程輪詢到這條消息時,就回呼該 Handler 的 handleMessage(msg)。「誰發出,誰處理」的閉環由此成立,這個設計相當漂亮。

4. Message:數據載體

你想讓主線程做什麼、帶什麼參數,總得有個東西裝著。Message 就是這個載體。

三、源碼解析

Looper

public final class Looper {
    // static 變數,可理解為 map:key 是線程,value 是該線程的 Looper
    static final ThreadLocal sThreadLocal = new ThreadLocal();
    // 主線程的 Looper 單獨持有,方便 getMainLooper() 高頻取用
    private static Looper sMainLooper;
    // 所屬線程的消息隊列
    final MessageQueue mQueue;
    final Thread mThread;

    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        // TLS 已有數據則拋異常:一個線程只能有一個 Looper
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

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

先補充一個前提:ThreadLocal 是線程本地儲存區(Thread Local Storage)。每個線程都有自己私有的區域,彼此無法存取對方的 TLS,這裡存的就是線程自己的 Looper。

仔細看 prepareMainLooper(),它做了兩件事:new 一個 Looper 放入靜態的 sThreadLocal,同時給 sMainLooper 賦值。之所以多留一個 sMainLooper,是因為主線程的 Looper 會被極高頻地獲取,直接走欄位比每次都去 ThreadLocal 查表更快。

Looper 的建構函數:

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

可以看到,此時才為當前線程建立 MessageQueue,並讓 Looper 持有其引用。prepareMainLooper() 執行完畢,主線程就從普通線程變成了 Looper 線程,此時它已經擁有一個 Looper 物件與一個消息隊列。

prepare() 的實現同理:先判斷 sThreadLocal 是否為 null,否則拋出「Only one Looper may be created per thread」。這既保證了 prepare 不可重複呼叫,也保證了一個線程只有一個 Looper 例項。

loop() 是整個機制的心臟:

public static void loop() {
    final Looper me = myLooper();       // 取出當前線程的 Looper
    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 是 Handler:誰把消息投進隊列,消息就持有它的引用
        msg.target.dispatchMessage(msg);
        msg.recycleUnchecked();         // 回收進消息池,下次用 obtain() 複用
    }
}

myLooper() 只是 return sThreadLocal.get()。若 me 為 null 則拋異常,也就是說 loop() 必須在 prepare() 之後執行。

兩個常見疑問

問題一:UI 線程一直卡在這個循環裡,主線程不會卡死嗎?還怎麼執行其他操作?

答案是:主線程此後執行的任何程式碼,都是被 Looper 從消息隊列中取出來執行的。生命週期回呼也不例外——系統服務 ActivityManagerService 透過 Binder 發出 IPC,App 進程收到後由 Binder 線程往主線程隊列插入一條消息,主線程輪詢到它時才執行 onCreate、onResume 等回呼。循環並不等於阻塞,它只是等待。

問題二:主線程優先級這麼高,死循環難道不會一直佔滿 CPU?其他線程怎麼辦?

這正是生產者—消費者模型的精妙之處。當 MessageQueue 沒有消息時,主線程會阻塞在 queue.next() 內部,此時它釋放 CPU 進入休眠,直到新消息抵達才被喚醒。2.2 版本之前這套機制用 wait/notify 實作,之後改為 Linux 的 pipe/epoll:透過往 pipe 寫入資料來喚醒主線程。原理類似 I/O,阻塞的讀寫不佔用 CPU 資源。

Handler

public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass())
                && (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: "
                    + klass.getCanonicalName());
        }
    }
    // 取得當前線程的 Looper
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
    }
    // 讓 Handler 持有當前線程消息隊列的引用
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

關鍵在最後兩行:Handler 建構時就綁定了所屬線程的 MessageQueue。順帶留意開頭那段 FIND_POTENTIAL_LEAKS 檢查——非靜態的匿名內部類、成員類、區域類 Handler 會打出洩漏警告,這不是牢騷,而是真實風險:Handler 持有外部 Activity 的隱式引用,延遲消息未處理完之前 Activity 無法被回收。callback 的優先級高於 handleMessage,但實務中較少使用。

sendMessage 系列方法輾轉多次後彙集到 sendMessageAtTime:

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) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;              // 關鍵:把 target 指向自己
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

enqueueMessage 中的 msg.target = this 是理解整個機制的鑰匙:它讓消息記住是哪個 Handler 發出的,最終入隊到該 Handler 所綁定的 MessageQueue。回到 loop() 就能看到閉環——取出消息後交給 msg.target.dispatchMessage(msg)。

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

public void handleMessage(Message msg) {
}

handleMessage 是一個空方法——因為最終要怎麼處理消息完全由我們決定。實務中都是覆寫它,再按 msg.what 分派:

private Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case value:
                break;
            default:
                break;
        }
    }
};

四、串起來複習一遍

  1. Looper.prepare() 在當前線程存入一個 Looper 例項,該例項內部持有 MessageQueue。由於 prepare 每線程只能呼叫一次,MessageQueue 天然也是每線程唯一。
  2. Looper.loop() 讓當前線程進入無限循環,不斷從 MessageQueue 取消息,交由 msg.target.dispatchMessage(msg) 處理。
  3. Handler 建構時取得當前線程的 Looper,進而關聯其 MessageQueue。
  4. Handler.sendMessage() 先把 msg.target 指向自己,再把消息投入 MessageQueue。
  5. 建立 Handler 時覆寫的 handleMessage,就是 dispatchMessage 最終呼叫的方法。

最後回答一個常被問到的問題:Activity 裡我們從沒顯式呼叫 Looper.prepare() 和 Looper.loop(),為什麼 Handler 能正常建立?因為在 Activity 的啟動流程中,框架早已經在這個 UI 線程上完成過這兩步。如果你想在其他線程用 Handler,就必須自己先跑 prepare(),用完再呼叫 Looper.myLooper().quit() 讓循環退出,否則線程會一直懸在那裡無法結束。

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