編輯:關於 Android 程式設計
Android 的消息處理機制是其執行緒通訊的核心,理解 Looper 與 Handler 對開發者來說是必備知識。本文將從基本概念出發,深入剖析源碼並說明如何在多執行緒環境下安全更新 UI。
Message:消息,其中包含了消息ID,消息處理對象以及處理的數據等,由MessageQueue統一列隊,終由Handler處理。 Handler:處理者,負責Message的發送及處理。使用Handler時,需要實現handleMessage(Message msg)方法來對特定的Message進行處理,例如更新UI等。 MessageQueue:消息隊列,用來存放Handler發送過來的消息,並按照FIFO規則執行。當然,存放Message並非實際意義的保存,而是將Message以鏈表的方式串聯起來的,等待Looper的抽取。 Looper:消息泵,不斷地從MessageQueue中抽取Message執行。因此,一個MessageQueue需要一個Looper。 Thread:線程,負責調度整個消息循環,即消息循環的執行場所。
Android 系統的消息隊列和消息循環都是針對具體執行緒的:一個執行緒可以存在(當然也可以不存在)一個消息隊列和一個消息循環(Looper),特定執行緒的消息只能分發給本執行緒,不能跨執行緒、跨進程通訊。但建立的工作執行緒預設是沒有消息循環和消息隊列的,若想讓該執行緒具備消息隊列和消息循環,需要在執行緒中先呼叫 Looper.prepare() 建立消息隊列,再呼叫 Looper.loop() 進入消息循環。如下所示:
LooperThread Thread { Handler mHandler; run() { Looper.prepare(); mHandler = Handler() { handleMessage(Message msg) { } }; Looper.loop(); } }
下面一起來分析 Looper 類的源碼,每個重要行的上方都會加上註解:
public class Looper { //static變量,判斷是否打印調試信息。 private static final boolean DEBUG = false; private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; // sThreadLocal.get() will return null unless you've called prepare(). //線程本地存儲功能的封裝,TLS,thread local storage //因為存儲要麼在棧上,例如函數內定義的內部變量;要麼在堆上,例如new或者malloc出來的東西 //但是現在的系統比如Linux和windows都提供了線程本地存儲空間,也就是這個存儲空間是和線程相關的 private static final ThreadLocal sThreadLocal = new ThreadLocal(); //消息隊列,MessageQueue final MessageQueue mQueue; volatile boolean mRun; //和本looper相關的那個線程,初始化為null Thread mThread; private Printer mLogging = null; //static變量,代表一個UI Process的主線程 private static Looper mMainLooper = null; //往TLS中設上這個Looper對象,如果這個線程已經設過了looper的話就會報錯 //這說明,一個線程只能設一個looper public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper()); } //由framework設置的UI程序的主消息循環,注意,這個主消息循環是不會主動退出的 public static final void prepareMainLooper() { prepare(); setMainLooper(myLooper()); if (Process.supportsProcesses()) { myLooper().mQueue.mQuitAllowed = false; } } private synchronized static void setMainLooper(Looper looper) { mMainLooper = looper; } public synchronized static final Looper getMainLooper() { return mMainLooper; } //消息循環,整個程序就在這裡while了 public static final void loop() { Looper me = myLooper();//從該線程中取出對應的looper對象 MessageQueue queue = me.mQueue;//取消息隊列對象 while (true) { Message msg = queue.next(); // might block取消息隊列中的一個待處理消息 if (msg != null) { if (msg.target == null) { // No target is a magic identifier for the quit message. return; } msg.target.dispatchMessage(msg); msg.recycle(); } } } //返回和線程相關的looper public static final Looper myLooper() { return (Looper)sThreadLocal.get(); } public static final MessageQueue myQueue() { return myLooper().mQueue; } //創建一個新的looper對象,內部分配一個消息隊列,設置mRun為true private Looper() { mQueue = new MessageQueue(); mRun = true; mThread = Thread.currentThread(); } public void quit() { Message msg = Message.obtain(); mQueue.enqueueMessage(msg, 0); } public Thread getThread() { return mThread; } }
那該怎麼往這個消息隊列中發送消息呢?呼叫 Looper 的 static 函式 myQueue 可以取得消息隊列,你就能自己往裡面插入消息。不過這種方法比較麻煩,這時候 Handler 類就派上用場了。先來看看 Handler 的源碼:
class Handler{ //handler默認構造函數 public Handler() { //獲取本線程的looper對象,如果本線程還沒有設置looper,這回拋異常 mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } //把looper的queue和自己的queue設為同一個 mQueue = mLooper.mQueue; mCallback = null; } //由外部設置looper public Handler(Looper looper) { mLooper = looper; mQueue = looper.mQueue; mCallback = null; } //帶callback的,一個handler可以設置一個callback public Handler(Looper looper, Callback callback) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; } //通過handler發送消息,調用了內部的一個sendMessageDelayed 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) { boolean sent = false; MessageQueue queue = mQueue; if (queue != null) { //把消息的target設置為自己,然後加入到消息隊列中 msg.target = this; sent = queue.enqueueMessage(msg, uptimeMillis); } else { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); } return sent; } //從消息隊列中得到一個消息後,會調用它的target的dispatchMessage函數 public void dispatchMessage(Message msg) { //如果msg本身設置了callback,則直接交給這個callback處理了 if (msg.callback != null) { handleCallback(msg); } else { //如果該handler的callback有的話,則交給這個callback處理了 if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } //否則交給派生處理 handleMessage(msg); } } }
產生一個 Message:
Message msg = mHandler.obtainMessage(); msg.what = what; msg.sendToTarget();
發送:在 Handler.java 的 sendMessageAtTime 方法中,我們看到它找到所引用的 MessageQueue,然後將 Message 的 target 設定成自己(目的是為了在處理消息環節,Message 能找到正確的 Handler),再將這個 Message 納入消息隊列中。
MessageQueue queue = mQueue; if (queue != null) { msg.target = this; sent = queue.enqueueMessage(msg, uptimeMillis); }
抽取:在 Looper.java 的 loop() 函式裡,有一個死循環,不斷地從 MessageQueue 中取出下一個 Message,再透過 Message 中攜帶的 target 資訊交給正確的 Handler 處理。
Looper me = myLooper(); MessageQueue queue = me.mQueue; while (true) { Message msg = queue.next(); // might block if (msg != null) { if (msg.target == null) { // No target is a magic identifier for the quit message. return; } msg.target.dispatchMessage(msg); msg.recycle(); } }
處理:在 Handler.java 的 dispatchMessage 方法裡,其中一個分支就是呼叫 handleMessage 來處理這條 Message,這也正是使用 Handler 時需要實作 handleMessage 的原因。
if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); }
至此我們看到,一個 Message 經由 Handler 的發送、MessageQueue 的入隊、Looper 的抽取,又再一次回到 Handler 的懷抱。而繞的這一圈,也正好幫助我們將同步操作變成了異步操作。
在主執行緒(UI 執行緒)裡,如果建立 Handler 時不傳入 Looper 物件,那麼將直接使用主執行緒的 Looper 物件(系統已幫我們建立好);在其他執行緒裡,如果建立 Handler 時不傳入 Looper,那麼這個 Handler 將無法接收處理消息。通用做法是:
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
在建立 Handler 之前,為該執行緒準備好一個 Looper(Looper.prepare),然後讓這個 Looper 跑起來(Looper.loop)抽取 Message,這樣 Handler 才能正常工作。因此,Handler 處理消息總是在建立 Handler 的執行緒裡運行。由於消息處理中不乏更新 UI 的操作,而不正確的執行緒直接更新 UI 將引發異常,所以要時刻關心 Handler 在哪個執行緒裡建立。
SDK 告訴我們,有以下 4 種方式可以從其他執行緒存取 UI 執行緒:
· Activity.runOnUiThread(Runnable)
· View.post(Runnable)
· View.postDelayed(Runnable, long)
· Handler
其中特別說明 View.post(Runnable):在 post 方法裡,View 取得當前執行緒(即 UI 執行緒)的 Handler,然後把 action 物件 post 到 Handler 裡;Handler 把傳來的 action 包裝成一個 Message(callback 為 action),投入 UI 執行緒的消息循環中。當 Handler 再次處理該 Message 時,其中一條分支就是直接呼叫 runnable 的 run 方法,而此時已經路由到 UI 執行緒裡,因此可以毫無顧慮地更新 UI。
· Handler 的處理過程運行在建構 Handler 的執行緒裡
· 一個 Looper 對應一個 MessageQueue
· 一個執行緒對應一個 Looper
· 一個 Looper 可以對應多個 Handler
· 不確定當前執行緒時,更新 UI 時盡量呼叫 post 方法
OpenCV SfM 多目三維重建實作解析
本文使用的程式碼需要 OpenCV 3.0 以上版本,因為部分函数在 3.0 之後才提供。多目三維重建的目標,是從多張有序影像中還原相機位置與空間三維點。 問題簡化 為了
CyanogenMod 13.0 小米 4 源碼下載、編譯與 ROM 製作指南
前言 本文以小米 4 與 CyanogenMod 13.0 為例,整理從 Recovery 安裝、編譯環境準備、源碼下載、專有檔案提取,到 ROM 編譯與安裝的完整流程。
Android 搜索功能實戰:從關鍵字輸入到結果列表
在前一篇文章中,我們完成了「點擊發現按鈕自動加載熱門數據」的功能。今天則要進一步挑戰搜索:如何在搜索欄輸入關鍵字,並把符合條件的內容以列表形式呈現出來。這篇筆記會把整個流
Android AIDL 教學:用接口定義語言實現進程間通信
為了讓應用程式之間能彼此溝通,Android 提供了 IPC(Inter Process Communication,進程間通信)的一種獨特實作:AIDL(Android