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

Android 消息處理機制 Looper 與 Handler 深度詳解

編輯:關於 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 的懷抱。而繞的這一圈,也正好幫助我們將同步操作變成了異步操作。

Handler 所處的執行緒與更新 UI

在主執行緒(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 方法

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