編輯:關於 Android 程式設計
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 得以更新。
當應用程式啟動時,會依序經歷: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() 啟動輪詢。
按照傳統方式,我們依序閱讀:構造方法 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)); }
每次 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 物件。
先談 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;
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 的響應至此完成。
Android 事件分發機制(上):ViewGroup 如何分發觸控事件
Android 的觸控事件分發,是理解 View 與 ViewGroup 協作的核心。手指在螢幕上的每一次按下、滑動與抬起,都會被系統包裝成 MotionEvent,再由
深入 Android Dialog:八種常見彈窗效果的實作解析
Dialog 是 Android 裡使用頻率極高、變化也最多的元件。從最簡單的確認框,到列表、單選、多選、進度條與自訂版面,幾乎都能用 AlertDialog.Build
Android 取得三軸方向資料的兩種方案(磁力計+加速度計)
基礎概念 先釐清 Android 座標系統下三個旋轉角的定義: ・繞 Z 軸旋轉:Azimuth(方位角),可理解為指南針的磁北方向偏角。・繞 X 軸旋轉:Pitch(
Android 輸入法框架分析(一):三大元件
Android 輸入法框架(Input Method Framework,IMF)是極為重要的模組,它分布在三個部分(確切地說是三個行程):Client、IME 與 IM