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

Android 源碼剖析:Looper、MessageQueue、Message 與 Handler 的初始化及運作機制

編輯:關於 Android 程式設計

Handler 機制可以說是我入門源碼的第一課,看得格外仔細,收穫頗多,特此記錄。本文的順序是:先複習 Handler 的基本功,再逐行深入源碼。

一、Handler 的目的

Handler 機制最核心的目的,就是解決子執行緒更新 UI 執行緒控制項的問題。

二、四大元件的關係

關於 Handler、MessageQueue、Looper、Message 之間的關係,坊間書籍多有配圖,但既然本文以研讀源碼為主,這裡就以文字梳理它們的協作流程。

三、知識點總結

1)初始化順序必然是 Looper → MessageQueue → Handler。主 UI 執行緒會實例化 Looper(子執行緒則需手工實例化),Looper 中再實例化 MessageQueue;Handler 初始化時只會獲取 Looper 與 MessageQueue,因此必須先有 Looper,才能有 Handler。

2)Handler 中寫有操作主 UI 執行緒的 handleMessage 空方法,並可在子執行緒中透過 Handler 實例發送 Message。

3)一個執行緒只有一個 Looper,Looper 負責管理 MessageQueue。

4)主 UI 執行緒(ActivityThread)建立 Looper 物件,而 Looper 又建立了 MessageQueue。

5)Handler 使用 MessageQueue 的 enqueueMessage 插入消息,Looper 的 loop() 方法則呼叫 Handler 的 dispatchMessage() 分發消息,最終透過 handleMessage() 使主 UI 得以更新。

四、逐步分析 Handler 源碼

1. Looper 的獲取

當應用程式啟動時,會依序經歷:ActivityManager 的 startActivity() → ActivityThread 的 main() → Looper.prepareMainLooper() 實例化主 UI 執行緒的 Looper。

先來看 ActivityThread.main() 方法中的關鍵部分:

 public static void main(String[] args) { ... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); ... Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }

從可見,主 UI 執行緒 Looper 的初始化就靠 prepareMainLooper(),隨後再以 loop() 啟動輪詢。

2. Looper 源碼與 MessageQueue 實例化

按照傳統方式,我們依序閱讀:構造方法 Looper() → loop() 輪詢方法。

Looper 的構造方法為 private,可見其單例模式痕跡明顯:

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

類初始化時會建立 sMainLooper,並透過 prepareMainLooper() 進行初始化:

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

核心的 prepare() 方法透過 ThreadLocal 確保每條執行緒僅有一個 Looper:

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

3. loop() 輪詢方法

每次 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; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // 可能會阻塞 if (msg == null) { return; } msg.target.dispatchMessage(msg); msg.recycleUnchecked(); } }

簡化掉日誌相關程式碼後,整個輪詢迴圈其實只剩下三個關鍵動作:先以 myLooper() 取得 Looper 實例,接著取出 me.mQueue,然後在無窮迴圈中不斷透過 queue.next() 取出消息、再透過 msg.target.dispatchMessage(msg) 將消息分發出去。其中 msg.target 正是指向主執行緒中的 Handler 物件。

4. MessageQueue 與 Message

先談 MessageQueue。此前留下的 mQuitAllowed 參數,其實是用來判斷佇列能否退出的:

 // True if the message queue can be quit. private final boolean mQuitAllowed;

由於主 UI 執行緒的 Looper 傳入的 quitAllowed 一直是 false,因此主執行緒不允許 MessageQueue 退出。而自行建立的 Looper 則透過 prepare() 傳入 true,是可退出且需要退出的,使用完畢後應呼叫 Looper.quit() 結束迴圈。

Message 則是一個可序列化的物件,明顯用於傳輸資料。其中最常用的是 what 欄位,每個 Handler 都擁有獨立的命名空間,不必擔心命名衝突:

 public int what;

官方並不建議直接 new Message,而是推薦使用 obtain() 以複用 Message Pool 中的實例,藉此降低建立物件的開銷。此外,Message 還有一個關鍵的 target 欄位,用來指向當前使用的 Handler:

 /*package*/ Handler target;

5. Handler 機制

Handler 提供了一個 Callback 介面,方便在實例化時避免另寫子類;而 handleMessage() 則是子類用來接收並處理消息的方法。

建立 Handler 時,會透過 Looper.myLooper() 取得 Looper 實例,並據此取得 MessageQueue:

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

發送消息時,無論呼叫哪個方法,最終都會彙集到 sendMessageAtTime(),再透過 enqueueMessage() 真正把消息塞進 MessageQueue,同時設定 msg.target = this:

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

而當 Looper.loop() 呼叫 msg.target.dispatchMessage() 時,便回到 Handler 的 dispatchMessage(),它會依序嘗試 msg.callback、mCallback,最後交由我們重寫的 handleMessage() 處理,主 UI 的響應至此完成。

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