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

Android Handler 機制深度解讀:從源碼看消息循環

編輯:關於 Android 程式設計

一、為什麼需要 Handler

剛接觸 Android 開發時,很多人都在子線程更新 UI 時撞過這個異常:

android.view.ViewRoot$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.

意思是:只有創建視圖層級的那個線程才能操作它。既然 UI 只能在創建它的主線程中更新,那麼就需要一套機制讓子線程能「通知」主線程更新界面——這正是 Handler 的用武之地。它負責與子線程通訊,在子線程與 UI 線程之間架起橋樑,實現異步更新 UI。

二、Handler 機制的四大角色

說到 Handler 機制,繞不開四個類:Message、Looper、MessageQueue、Handler。

1. Message:消息類

Message 用於封裝消息,並可指定操作形式。使用時有幾個要點:

  • 雖然 Message 有 public 構造方法,但應通過 Message.obtain() 從消息池複用對象以節省資源;
  • 若只需傳遞簡單 int 信息,優先用 arg1、arg2,比 Bundle 更省內存;
  • 善用 what 字段標識消息類型,以便分類處理。

2. Looper:消息循環類

Looper 用於在一個線程中進行消息輪詢,讓普通線程變成能循環工作的 Looper 線程。創建方式是在 run() 中先調用 Looper.prepare(),再調用 Looper.loop():

public class LooperThread extends Thread {
    @Override
    public void run() {
        Looper.prepare();   // 初始化為 Looper 線程
        // ... 實例化 handler
        Looper.loop();      // 循環處理消息
    }
}

從源碼看,prepare() 會創建一個 Looper 實例並存入 ThreadLocal。由於 Looper 構造私有、且基於 ThreadLocal 存儲,每個線程只能有一個 Looper,prepare() 不能被調用兩次。而 loop() 則是一個無窮循環,不斷從 MessageQueue 中取出消息並交給 msg.target.dispatchMessage(msg) 分發——這裡的 target 正是發送消息的 Handler。

至於主線程,系統在啟動時已通過 prepareMainLooper() 為 UI 線程初始化了 Looper,所以我們無需手動調用即可用 getMainLooper() 拿到它。

3. MessageQueue:消息隊列

每個 Looper 內部維護一個 MessageQueue,按時間順序存放待處理消息。

4. Handler:消息操作類

Handler 用於向 MessageQueue 發送和處理 Message 與 Runnable,每個 Handler 實例關聯單個線程及其消息隊列。默認構造時它會綁定當前線程的 Looper:

mLooper = Looper.myLooper();
if (mLooper == null) {
    throw new RuntimeException(
        "Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;

因此在子線程中直接 new Handler() 會報錯,除非先調用 Looper.prepare()。這也說明了:一個線程可以有多個 Handler,但只有一個 Looper。

三、消息的發送與處理

發送消息最終都會走到 sendMessageAtTime(),其中 msg.target = this 把當前 Handler 設為消息的 target,確保 Looper 執行到該消息時能找到對應的 Handler。而 post(Runnable) 本質上也是把 Runnable 封裝進 Message 的 callback 字段。

處理環節由 dispatchMessage() 完成,它按優先級依次判斷:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);        // 優先執行 Runnable 回調
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;             // 其次交給 Callback 接口
            }
        }
        handleMessage(msg);         // 最後由自身 handleMessage 處理
    }
}

由此可見,Handler 是在它關聯的 Looper 線程中處理消息的。常見做法就是:在 Activity 中創建 Handler 並把引用傳給工作線程,工作線程完成任務後用 Handler 發送消息,通知主線程更新 UI——這樣便優雅地解決了跨線程更新界面的問題。

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