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

深入剖析 Android Handler 消息機制(解惑篇)

編輯:關於 Android 程式設計

概述

對於 Android 中的消息處理機制,大家對其用法應該都不陌生,但對其工作原理,未必每個人都深入研究過。就像我們自己寫的類,用得越熟就越順手;如果我們真正理解了消息機制的具體實現,使用起来自然事半功倍。

博主此前只是稍有涉獵,心中仍存幾個疑問:既然 Looper.loop() 是一個死循環,它會不會很消耗 CPU?死循環阻塞了線程,其他事務又是如何被處理的?Android 的 UI 線程究竟在哪裡初始化?今天就把這些問題一次性說清楚。

Android 中線程的分類

帶有消息隊列、用來執行循環性任務的線程(例如主線程、android.os.HandlerThread):

有消息時就處理,沒有消息時就睡眠。

沒有消息隊列、用來執行一次性任務的線程(例如 java.lang.Thread):任務一旦執行完成便退出。

帶有消息隊列線程概述

四要素

Message(消息)、MessageQueue(消息隊列)、Looper(消息循環)、Handler(消息發送和處理)。

四要素的交互過程

具體工作過程包括:消息隊列的創建、消息循環、消息的發送與消息的處理。

最基本的兩個 API:

Handler.sendMessage:帶一個 Message 參數,用來描述消息的內容。

Handler.post:帶一個 Runnable 參數,會被轉換為一個 Message 參數。

基於消息的異步任務接口

android.os.HandlerThread:適合用來處理不需要更新 UI 的後台任務。

android.os.AsyncTask:適合用來處理需要更新 UI 的後台任務。

帶有消息隊列線程的具體實現

ThreadLocal

ThreadLocal 並不是一個 Thread,而是 Thread 的局部變量。當使用 ThreadLocal 維護變量時,它為每個使用該變量的線程提供獨立的變量副本,因此每個線程都可以獨立改變自己的副本,而不影響其他線程對應的副本。從線程的角度看,目標變量就像線程的本地變量,這也是類名中「Local」的含義。

Looper

Looper 用於在指定線程中運行一個消息循環,一旦有新任務則執行,執行完繼續等待下一個任務,即成為 Looper 線程。Looper 類的註釋中有這樣一個例子:

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

核心程式碼其實就兩行,先來看 Looper.prepare() 的具體實現:

 public final class Looper { static final ThreadLocal sThreadLocal = new ThreadLocal(); private static Looper sMainLooper; final MessageQueue mQueue; final Thread mThread; private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } public static void prepare() { prepare(true); } 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)); } 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() 的核心就是將 Looper 物件定義為 ThreadLocal;

一個 Thread 只能有一個 Looper 物件;

prepare() 會調用 Looper 的構造方法,初始化一個消息隊列,並指定當前線程;

在調用 Looper.loop() 之前,必須確保已調用 prepare(),並可調用 quit 方法結束循環。

說到初始化 MessageQueue,它是什麼呢?官方註釋說明:它是一個低等級的、持有 Messages 集合的類,被 Looper 分發。Messages 並不是直接加到 MessageQueue 的,而是透過 Handler 物件與 Looper 關聯到一起。我們可以透過 Looper.myQueue() 來檢索當前線程的 MessageQueue。

接下來看看 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; final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); if (msg == null) { return; } Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed ..."); } msg.recycleUnchecked(); } }

由此可見,調用 loop 方法後,Looper 線程就開始真正工作,它不斷從自己的 MessageQueue 中取出隊頭的消息(任務)來執行。

除了 prepare() 和 loop(),Looper 還有一些有用的方法:

Looper.myLooper():得到當前線程的 Looper 物件;

getThread():得到 Looper 物件所屬線程;

quit():結束 Looper 循環。

需要注意,quit() 實際上調用的是 MessageQueue 的 quit(boolean safe) 方法:

 void quit(boolean safe) { if (!mQuitAllowed) { throw new IllegalStateException("Main thread not allowed to quit."); } synchronized (this) { if (mQuitting) { return; } mQuitting = true; if (safe) { removeAllFutureMessagesLocked(); } else { removeAllMessagesLocked(); } nativeWake(mPtr); } }

可見主線程是不能調用這個方法退出消息隊列的。mQuitAllowed 參數在 Looper 初始化時設定,主線程初始化調用的是 Looper.prepareMainLooper(),它將參數設為 false。

Message

在整個消息處理機制中,Message 又叫 task,封裝了任務攜帶的資訊和處理該任務的 Handler。這個類定義了一個包含描述和任意類型物件的物件,它可以被發送給 Handler。

從註釋中可以了解到:

儘管 Message 有 public 的預設構造方法,但應透過 Message.obtain() 從消息池中獲得空消息物件,以節省資源。

如果消息只需攜帶簡單的 int 資訊,請優先使用 Message.arg1 和 Message.arg2,這比用 Bundle 更省記憶體。

用 message.what 來標識資訊,以便用不同方式處理消息。

Handler

從 MessageQueue 的註釋可知,添加消息到消息隊列是透過 Handler 來操作的。每一個 Handler 實例關聯了一個單一的 thread 和這個 thread 的 message queue,當 Handler 實例被創建時,它就被綁定到創建它的 thread。它用來調度 message 和 runnables 在未來某個時間點執行,還可以排列其他線程裡執行的操作。

 public class Handler { final MessageQueue mQueue; final Looper mLooper; public Handler() { this(null, false); } public Handler(Looper looper) { this(looper, null, false); } 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; } }

先看構造方法,其中的重點是初始化了兩個變量,把關聯 Looper 的 MessageQueue 作為自己的 MessageQueue,因此它的消息將發送到關聯 Looper 的 MessageQueue 上。

有了 Handler 之後,就可以使用它提供的 post 和 send 系列方法向 MessageQueue 發送消息。post 發出的 Runnable 物件最後都被封裝成 Message 物件。

來看 Handler 如何發送消息:

 public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 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) { MessageQueue queue = mQueue; if (queue == null) { return false; } return enqueueMessage(queue, msg, uptimeMillis); } private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

分析這條調用鏈:

調用 getPostMessage(r),把 Runnable 物件添加到一個 Message 物件中。

sendMessageDelayed 基本沒做什麼,又繼續調用 sendMessageAtTime,在這個方法裡拿到創建這個 Handler 的線程持有的 MessageQueue。

調用 enqueueMessage,給 msg 的 target 變量賦值為當前的 Handler 物件,然後放入 MessageQueue。

由於 message.target 為該 Handler 物件,這確保了 Looper 執行到該 message 時能找到處理它的 Handler,即 loop() 方法中的關鍵代碼 msg.target.dispatchMessage(msg)。

消息最終如何被處理?看 dispatchMessage:

 public interface Callback { public boolean handleMessage(Message msg); } public void handleMessage(Message msg) { } public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } private static void handleCallback(Message message) { message.callback.run(); }

可以看到,這裡最終調用到了我們重寫的 handleMessage(Message msg) 來處理子線程發來的消息,或者調用 handleCallback 去執行子線程中定義並傳過來的操作。

深入思考

為什麼要有 Handler 機制

我們如何在子線程更新 UI?——使用 Handler 機制傳遞消息到主線程(UI 線程)。

為什麼不在子線程更新 UI?——因為 Android 是單線程模型。

為什麼要做成單線程模型?——多線程並發訪問 UI 可能導致 UI 控件處於不可預期的狀態。若加鎖雖能解決,但缺點明顯:一是鎖機制讓 UI 訪問邏輯變得複雜,二是加鎖導致效率低下。

Handler 機制與命令模式

仔細分析不難看出,Handler 機制其實是一個非典型的命令模式。

接收者:Handler,執行消息處理操作。

調用者:Looper,調用消息的處理方法。

命令角色:Message,消息類。

客戶端:Thread,創建消息並綁定 Handler(接收者)。

Android 主線程如何管理子線程消息

Android 上一個應用的入口應該是 ActivityThread,和普通的 Java 類一樣,入口是一個 main 方法。

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

可以看到,我們在這裡初始化了主線程(UI)的 Looper 並啟動它,之後就可以處理子線程和其他組件發來的消息了。

為什麼主線程不會因為 loop() 裡的死循環卡死

這裡涉及的東西比較多,概括的理解是這樣:

為什麼不會卡死:

Handler 機制是使用 pipe(管道)來實現的,主線程沒有消息處理時會阻塞在管道的讀端。

Binder 線程會往主線程消息隊列裡添加消息,然後往管道寫端寫一個字節,這樣就能喚醒主線程從管道讀端返回,也就是說 queue.next() 會返回。

主線程大多數時候都處於休眠狀態,並不會消耗大量 CPU 資源。

既然是死循環,又如何處理其他事務呢?答案是透過創建新線程的方式。

main 方法裡調用了 thread.attach(false),這裡會創建一個 Binder 線程(具體指 ApplicationThread,即 Binder 的服務端,用於接收系統服務 AMS 發送來的事件),該 Binder 線程透過 Handler 將 Message 發送給主線程。

ActivityThread 對應的 Handler 是一個內部類 H,裡面包含了啟動 Activity、處理 Activity 生命週期等方法。

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