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

Android 5.0 Handler 訊息機制源碼流程深度解析

編輯:關於 Android 程式設計

本文僅作為個人學習記錄,內容多彙整自網路上各路高手的精彩分享,在此摘錄並以自己的理解方式重新整理。接下來就開始學習並梳理 Handler 機制。

1、概述

在 Android 平台上,主要有兩種通訊機制:一種是行程間的通訊——Binder 機制;另一種是 Handler 訊息機制,屬於行程內部的通訊機制。當然除此之外還有 Socket、管道等,這裡先聚焦於 Handler 機制。

整體而言,Handler 機制就是:訊息發送者將訊息發送到訊息佇列,而訊息佇列中有一個循環處理器,不斷循環處理收到的訊息。

網路上的示意圖:

基本的三大概念:

1、訊息發送者。例如兩個線程之間通訊,發送者就屬於當前線程。

2、訊息佇列。名字雖叫「佇列」,但最終這個佇列其實是一條類似鏈結串列的資料集合,並非佇列這種資料結構(按照時間順序排列)。

3、訊息循環處理。Android 把右半部封裝成了一個 Looper 類別,這個類別內部有佇列 MessageQueue 與循環函式 loop。但要注意,Looper 無法憑空運行起來,因此必須寄居於某個線程,而且每個線程最多只能有一個 Looper。這是怎麼保證的呢?看下面的 prepare 函式(暫時只考慮標準呼叫流程,非標準情況後文也會分析,屆時會報錯)。

 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 都需要先呼叫它的 prepare 函式。在 prepare 中,利用 Java 的 ThreadLocal 類別,往當前運行的線程中存入一個區域變數,最終存入了 ThreadLocal.ThreadLocalMap 當中,以 key = Looper.sThreadLocal(每個線程都一樣)、value = new Looper 的方式存入。由於每個 Thread 的 ThreadLocalMap 不同(透過每個 Thread 的 ID 來保證),所以即使 key 相同,取出來時也是自己存入的內容,彼此互不影響。

此處可以理解為:每個線程都為自己保存了一個 Looper 物件,且可以透過 ThreadLocal 的 get 方法取得這個物件,各線程之間相互不影響。在一些需要判斷的地方,透過 sThreadLocal 的 get 方法,會自動從當前線程中以相關的 key 取出存入的 value 值。一旦 sThreadLocal.get() != null,證明前面已經設定過,就會拋出異常。

那麼一定要先 prepare 嗎?這就要結合 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."); } .......}

 public static Looper myLooper() {

return sThreadLocal.get(); }

綜上可以看出,呼叫 loop 進行循環前,假如沒有 prepare,me == null 便直接拋出異常。loop 的操作你總是要做的,不然怎麼處理訊息呢?那麼為什麼在主線程中使用的時候也沒有呼叫 loop 呢?後文再分析。

Android 訊息機制中另一個關鍵類別是 Handler。當訊息循環器在其寄居的線程裡正式運作後(loop),訊息發送者就可以透過該 Looper 對應的 Handler,向這個訊息循環發出事件。

網路上的示意圖:

當你建構完 Handler 之後,就可以透過取得目標線程的 Handler 物件,然後往目標線程發送訊息了。最終的處理仍是由目標線程的訊息佇列與 loop 配合完成,如此便實現了同一行程內兩個不同線程之間的通訊。

注意:一個線程也可以有多個 Handler 進行存取(只要這個 Handler 屬於這個 Looper),但他們的 MessageQueue 只有一個,因為由前面可知 Looper 只有一個,而 Looper 中封裝的正是 MessageQueue。

注意:一旦取得這個線程的 Looper 物件以後,就可以透過這個 Looper 來獲得一個對應的 Handler 物件,這個 Handler 物件就能往該 Looper 對應的 MessageQueue 中發送訊息了。但處理回呼仍然是這個 Handler,因為一個 Looper 可以有多個 Handler。所以系統提供了取得主線程 Looper 物件的函式,便於與主線程通訊。

2、使用

基本的使用方法十分簡單,網路上也是一大堆,此處不再記錄。這裡先分享幾個概念與個人理解。

行程:感覺可以用一個 CPU 任務調度的概念來理解,完成一次「什麼什麼」的操作。當你開始申請行程的時候,CPU 會為這個行程開闢資源空間、複製資料等等;當完成這次調度之後,就會銷毀它。

每個行程啟動的時候都會有一條主線程,這條主線程貫穿整個行程的始終,在它的執行時間段內,可以分化出很多子線程。對於 Android 的 UI 操作,考慮到安全性,只允許在主線程進行操作。要注意這個主線程的概念——剛進入一個 App 就已經開始執行這條主線程,此時你從這個畫面跳轉到另一個畫面,它還是在主線程上進行的操作。要理解這個概念。

下面開始討論 Handler、Looper 的用法。

對於 Handler:

1、建構:它的建構有許多種重載,其實就是 Looper、Callback、boolean async 這三個參數初始化值的問題。此處先不討論 Callback、async 的賦值問題——Callback 好像是透過 Handler 內部介面 Callback 實作時覆寫我們的 Handler 的 handleMessage,有興趣可以去看一下 Handler 中的 dispatchMessage 方法;async 為 true 時,表示當前是個非同步的 Handler,發出的訊息為非同步訊息。本文重點在於理解整個 Handler 機制,暫未分析這兩個參數。

最常用的是空建構 Handler()——>Handler(Callback callback, boolean async)。首先它就會檢查 Looper.myLooper(),取得的就是線程本地儲存區中存放的 Looper,假如沒有執行過相應程式碼(prepare)時它就會為 null;假如為 null,那麼就會拋出異常。只有呼叫 Looper.prepare() 才能順利實例化(無論是系統中呼叫的還是你呼叫的)。由此也可以看出,你想要發送訊息,肯定要實例化 Handler,你實例化它,就必須先 prepare,不然會出問題。

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

第二常用的是 new Handler(Looper)——>new Handler(Looper looper, Callback callback, boolean async)。實例化時看起來不呼叫 prepare 沒事,但你肯定會呼叫 loop 讓它循環跑起來,由前面 loop 方法中也會進行檢查(由於沒有 set),到時候一樣會報錯。

 public Handler(Looper looper, Callback callback, boolean async) {

mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }

對於 Looper:

1、它是一個 final 的類別,並且建構子是私有的,且只在本類別的 prepare 中進行了 new。建構子中實例化了一個 MessageQueue,用來處理和存放訊息(存放的只是 Java 層的訊息,現在 Looper 在底層也有實作,功能更為強大),以及當前所在的線程 mThread。

 private Looper(boolean quitAllowed) {

mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }

對於 MessageQueue,此處先簡單看一下它的建構流程:

 MessageQueue(boolean quitAllowed) {

mQuitAllowed = quitAllowed;//設定是否允許退出線程,主線程是不允許退出的。 mPtr = nativeInit();//這個 long 類型最終指向了本地的 NativeMessageQueue 物件。 } private native static long nativeInit();

可以看到 nativeInit 是一個本地方法,透過 JNI 呼叫到 android_os_MessageQueue.cpp。

 static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {

NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue(); if (!nativeMessageQueue) { jniThrowRuntimeException(env, "Unable to allocate native queue"); return 0; } nativeMessageQueue->incStrong(env); return reinterpret_cast<jlong>(nativeMessageQueue); //強制轉換為把本地的物件 nativeMessageQueue 返回回去。}

從源碼中看 mPtr,最大的用途就是在 MessageQueue 的 next() 函式內呼叫 nativePollOnce(ptr, nextPollTimeoutMillis),使線程等待時用於往底層傳入變數,底層要使用。注意在 NativeMessageQueue 的建構中實例化了一個本地的 Looper 物件。

 NativeMessageQueue::NativeMessageQueue() : mInCallback(false), mExceptionObj(NULL) {

mLooper = Looper::getForThread(); if (mLooper == NULL) { mLooper = new Looper(false); Looper::setForThread(mLooper); }}

注意:Java 層的 Looper 物件和底層的 Looper 物件並不是同一個物件,它們各司其職,共同完成整個訊息機制。上層的 Looper 用來完成訊息佇列的建立與訊息的循環檢查;而 native 層的 Looper 主要是用來透過 Linux 的 epoll 機制實現等待/喚醒,以及對底層訊息的分發處理。也可以看出,有 Java 層的 Looper 物件,就一定有一個與它對應的 native 層 Looper 物件;但要注意,有 native 層的不一定需要 Java 層的 Looper,例如 input 系統中的 InputDispatcher。

接下來,對於 Looper 的實例,其它類別只能透過如下兩個介面進行取得:

 /** Returns the application's main looper, which lives in the main thread of the application.

*/ public static Looper getMainLooper() { synchronized (Looper.class) { return sMainLooper; } }

 /**

* Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static Looper myLooper() { return sThreadLocal.get(); }

2、在使用訊息機制前,Looper 循環器必須已經實例化,且存入到它所在的線程的本地儲存區當中,key 為成員變數 sThreadLocal(沒有循環器,你怎麼讀取訊息?)。那麼這個實例化並存入到所在線程本地的操作是什麼時候執行的呢?尤其是在主線程中直接 new Handler 使用,也沒有看到實例化 Looper。

談一些個人概念理解:主線程和其它線程一樣,只不過優先級可能高一點。Android 應用程式是訊息驅動的,在應用程式中,主線程也是圍繞著它的訊息佇列無限循環,直到應用退出。如果佇列中有訊息並且訊息已到時,那么就分發給相應的 Handler 處理;如果佇列中沒有符合條件的訊息,那麼主線程也不會一直空轉,而會空閒等待,直到下一個訊息的到來。個人理解要注意此時的空閒等待,不是我們平常所說的 ANR 出現的地方,不是說這邊等了一定時長沒訊息後系統就會出現 ANR。這塊是整個線程一直在循環工作的地方,如主線程就一直在這個循環中跑,等訊息、分發處理訊息等等。當你再在這個循環中處理某些耗時操作的時候,才有可能出現 ANR。

在主線程中:

行程啟動時,會啟動一條主線程,然後在 ActivityThread 類別的 main 方法中,完成了對 Looper 的初始化以及循環呼叫。問題:這個主線程在哪體現的?ActivityThread 我看也不是線程類別啊?(暫不懂)

另一個需要注意的問題:執行完 Looper.loop 後,當前的線程會進入到一個循環當中,界面上看就是一直卡死在這裡,等待訊息過來。所以你在 OnCreate 中再次執行這個會導致畫面無法顯示、無法完成 OnCreate。你要是在 Looper.loop() 後面還有一些必須的參數的實例化,它們也會執行不到,完成不了實例化。

下面摘取行程啟動流程的一部分,至於行程啟動的流程,大家可以去看羅升陽老師的部落格。

 public static void main(String[] args) {

...... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }

已經看到會先執行 prepareMainLooper 方法。所以此時有個限定,就是無論你在主線程還是子線程中都不可以再呼叫 prepareMainLooper 了,因為很明顯它會拋出異常。所以這個 prepareMainLooper 其實就是讓系統呼叫的。

 public static void prepareMainLooper() {

prepare(false); synchronized (Looper.class) { if (sMainLooper != null) {//由於第二次呼叫的時候這裡不為 null,那麼必然報錯。 throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }

在執行 prepareMainLooper 方法中,會先執行 prepare(false),執行這個操作的時候就會 new 一個 Looper 物件,然後把它以 key = sThreadLocal 存入到本地儲存區域,接著再賦值給 sMainLooper。

 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 的初始化,此步驟是源碼內部實現的(myLooper 和 sMainLooper 都有值了)。所以你在主線程中實例化 Handler 時可以直接 new Handler(),不需要傳入 Looper 物件,因為早已有了。假如你非要傳入的話,透過一開始的兩個介面獲得 Looper 實例然後傳入,呼叫另外重載的建構,這也是一樣的,沒啥影響。

在子線程中:

子線程中就沒有上面的便利了,你 new 出來新的線程後,不會自動地呼叫 prepare,然後去 loop。此時有如下幾種錯誤,根據前面相關建構和方法的分析:

假如你直接 new Handler() 的時候 Looper.myLooper() == null,會拋出異常。

假如你 new Handler(Looper.myLooper()),由於傳入帶 Looper,最終會走到三個參數的建構進行賦值。但是 mQueue = looper.mQueue,由於傳入的參數 Looper.myLooper() 為 null,導致 looper 為 null,進而 mQueue = looper.mQueue 也會出現 looper == null 的報錯。

假如你 new Handler(Looper.getMainLooper()),此時 sMainLooper 肯定不為 null,那麼 mQueue = looper.mQueue 不會報錯,看起來能往下走。但是當你執行 looper.loop() 開始輪詢的時候,會執行如下程式碼:final Looper me = myLooper();,myLooper 函式就是呼叫 sThreadLocal.get() 去取得當前正在運行的線程存入的區域變數 Looper,此時由於沒有 prepare 肯定為 null。在 looper 中有如下判斷:

if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); }

最後也會拋出異常。

綜上,你必須在當前線程中呼叫 Looper.prepare()(注意你不能呼叫 main 的 prepare,會出錯)。下面對 prepare 做出簡單分析:

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

首先可以看出,多次 prepare 由於 get 不為 null 會拋出異常;然後就是實例化一個 Looper 為這個 Thread,並且存放到當前線程的本地儲存區,以 key = sThreadLocal。所以在你實例化 Handler 的時候,先呼叫 prepare,然後你再用空建構或者 new Handler(Looper.myLooper()) 都不會報錯了,因為 new Handler(Looper.myLooper()) 是正確的 looper。

此處有個核心知識點:可以透過傳入的 looper 物件來獲得一個新的 Handler,然後就可以往對應的 Looper 中的 MessageQueue 中發送訊息了。要特別注意:myLooper 是從當前線程的本地儲存區當中取值,取出的就是前面 Looper.prepare() 放的,所以自己線程的循環還是輪詢起來了。

注意事項:一定要注意 Handler 的定義位置,很多時候你以為定義到了子線程中,其實還定義在主線程中。只有在子線程的類別中,或者 run 方法中定義了,才會跑到子線程中。

3、內部源碼實現

由於 Android 中實現的訊息機制用到了下面兩個技術點,為了更好地認識 Handler 機制,分別把下面的知識點做了整理。

3.1 Java 中的線程本地儲存技術 ThreadLocal 類別。

3.2 Linux 下的 epoll 機制初識。

3.3 訊息分隔符/同步分隔欄說明。

它就是訊息的一種。Message 有三種類型:

a、普通 Message。它的成員變數 target 為發送 Message 的 Handler 自己,透過入隊時的函式進行了賦值處理。

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

msg.target = this;// 當前的往外發送訊息的 Handler if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

b、非同步 Message。同樣是在呼叫 enqueueMessage 的時候判斷 mAsynchronous 是否為 true。mAsynchronous 是在 Handler 實例化的時候傳入的,如果為 true 那麼就呼叫 Message 的 setAsynchronous 設定為非同步訊息。

 public void setAsynchronous(boolean async) {

if (async) { flags |= FLAG_ASYNCHRONOUS; } else { flags &= ~FLAG_ASYNCHRONOUS; } }

c、Message 分隔符(同步分隔欄)。它是一種特殊的 Message,在佇列中作為一個分隔符,以它為標誌,後面的同步訊息即使已經到了觸發時間,也不會被 Looper 處理。MessageQueue 提供了 enqueueSyncBarrier(long when)、removeSyncBarrier 分別用於插入和移除分隔符。

 int enqueueSyncBarrier(long when) {

// Enqueue a new sync barrier token. // We don't need to wake the queue because the purpose of a barrier is to stall it. synchronized (this) { final int token = mNextBarrierToken++; final Message msg = Message.obtain(); msg.markInUse(); msg.when = when; msg.arg1 = token; Message prev = null; Message p = mMessages; if (when != 0) { while (p != null && p.when <= when) { prev = p; p = p.next; } } if (prev != null) { // invariant: p == prev.next msg.next = p; prev.next = msg; } else { msg.next = p; mMessages = msg; } return token; } }

 void removeSyncBarrier(int token) {

// Remove a sync barrier token from the queue. // If the queue is no longer stalled by a barrier then wake it. synchronized (this) { Message prev = null; Message p = mMessages; while (p != null && (p.target != null || p.arg1 != token)) { prev = p; p = p.next; } if (p == null) { throw new IllegalStateException("The specified message queue synchronization " + " barrier token has not been posted or has already been removed."); } final boolean needWake; if (prev != null) { prev.next = p.next; needWake = false; } else { mMessages = p.next; needWake = mMessages == null || mMessages.target != null; } p.recycleUnchecked(); // If the loop is quitting then it is already awake. // We can assume mPtr != 0 when mQuitting is false. if (needWake && !mQuitting) { nativeWake(mPtr); } } }

網路上的示意圖:

至於為什麼要這麼設計,暫時還想不到確切原因。我在源碼工程下搜尋整個 Android 目錄,發現除了 CTS 的測試套件,其它所有的系統應用都沒有呼叫這個。個人感覺可能和某些具體的訊息處理有關,比如有些訊息需要在什麼動作完成之後才能處理等等。而且在 Android 的訊息機制裡面,同步訊息和非同步訊息目前也就這點區別了(遇到分隔符時後面會不會被執行)。

3.3 訊息的發送:入隊、喚醒。

取得目標線程的 Handler 物件以後,就可以呼叫相應的發送訊息的方法,把訊息放入到 MessageQueue 當中。其實最終是放進它的成員變數 mPendingMessages(mMessages)所包含的 Message 物件,以及透過 Message 物件的 next 成員變數組成的一條鏈式訊息當中,這個訊息是按照觸發時間的順序排列的。

此處以一個標準的訊息發送過程來分析。在 Handler 中的流程如下:sendMessage——>sendMessageDelayed——>sendMessageAtTime——>enqueueMessage。

 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);//SystemClock.uptimeMillis() 開機到現在的時間。 }

 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {

MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

msg.target = this;// 當前的往外發送訊息的 Handler if (mAsynchronous) {//Handler 建構中傳入的用來標記是否是非同步的 Handler msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

然後會調入到 MessageQueue 中的 enqueueMessage 函式,嘗試去把訊息入隊。

 boolean enqueueMessage(Message msg, long when) {

//!!!注意 next 域的賦值,它是用來代表當前訊息的下一個要處理的訊息 if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w("MessageQueue", e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); //寫標誌位,讓人知道訊息正在使用。 msg.when = when;//發送的訊息處理的時間,當前系統時間或者是當前系統時間加上你延遲的時間。 Message p = mMessages;//mMessages 成員變數存放的就是當前訊息鏈條中觸發時間最靠前的那個訊息。 boolean needWake; //p == null 時是第一次往訊息鏈條插入;when == 0 時需要立刻處理這個訊息; //又或者 when < p.when 當前傳入的訊息的觸發時間小於以前在訊息鏈條最前面的訊息的觸發時間時候。 if (p == null || when == 0 || when < p.when) {//進入判斷後需要往訊息鏈條的頭部插入訊息。 // New head, wake up the event queue if blocked. msg.next = p;//此時原先的訊息鏈條的頭部訊息就放到了當前傳入的訊息的 next 變數中,用於下次處理。 mMessages = msg;//當前正在處理的 msg 設定為成員變數 mMessages,也就是訊息鏈條最前面最需要先觸發的訊息。 needWake = mBlocked; // 根據是否阻塞來決定是否要喚醒。//一般走到這的話,應該就為 true 了,需要喚醒一下。 } else { // 這樣就不是插入訊息鏈條頭部了,而是插入到鏈條當中某個合適的位置,所以不需要調整喚醒時間。 needWake = mBlocked && p.target == null && msg.isAsynchronous();//needWake 為 true 時插入的肯定是「同步分隔欄」(p.target == null && msg.isAsynchronous())。 Message prev; for (;;) {//循環找合適的位置,按照觸發時間進行排序 prev = p; p = p.next; //配合 prev = p 就這樣一直循環地找合適位置。 if (p == null || when < p.when) {//下一個訊息是 null 或者當前訊息的觸發時間小於某個訊息的觸發時間時,找到正確位置退出循環。 break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; //在前面找到合適位置 when < p.when,所以此時的 p 應該是 msg 下一個需要處理的訊息 prev.next = msg;// prev 是當前訊息的前一個需要處理的訊息。 } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { //需要喚醒就喚醒,就是往管道中寫入一個字符「w」,這樣 epoll 機制就監聽到了事件,然後處理。 nativeWake(mPtr); } } return true; }

這樣就完成把當前訊息插入到了訊息鏈條中,也把 msg.next 域做了正確處理(下一個要處理的訊息)。nativeWake 是一個 Java 本地方法,透過 JNI 技術呼叫到稍微底層一點的函式:private native static void nativeWake(long ptr);,呼叫到 android/framework/base/core/jni/android_os_MessageQueue.cpp 當中的 android_os_MessageQueue_nativeWake 方法。

 static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {

//可以看出來 ptr 被強制轉換成 *nativeMessageQueue 指標物件。 NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr); return nativeMessageQueue->wake();//然後去呼叫它的 wake。}

NativeMessageQueue 就定義在當前檔案當中,它的 wake 方法實現如下:

 void NativeMessageQueue::wake() {

mLooper->wake();}

呼叫到了 Looper 中的 wake。千萬要注意,這個 Looper 可不是 Java 層的 Looper 物件,而是 C++ 實現的一個 Looper 物件,它位於 system/core/libutils/。在看 Looper 物件的 wake 函式之前,我們先看一下 Looper.cpp 的建構子。

 Looper::Looper(bool allowNonCallbacks) :

mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) { int wakeFds[2]; int result = pipe(wakeFds); //呼叫系統的 pipe 函式,建立一個管道。 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno); mWakeReadPipeFd = wakeFds[0]; mWakeWritePipeFd = wakeFds[1]; result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);//設定為非阻塞模式 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d", errno); result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);//設定為非阻塞模式 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d", errno); mIdling = false; // Allocate the epoll instance and register the wake pipe. mEpollFd = epoll_create(EPOLL_SIZE_HINT); //建立一個 epoll 句柄。 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno); struct epoll_event eventItem; memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union eventItem.events = EPOLLIN; //要監聽的事件 eventItem.data.fd = mWakeReadPipeFd; result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem); //注冊監聽事件。 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d", errno);}

總的來說就是建立了一個管道,然後初始化好一個 epoll 句柄,來監控這個管道的讀取端。到時候就會明瞭,不懂 epoll 的建議去看看基本的概念,不深入研究實現的話還是比較好理解的。

 void Looper::wake() {

#if DEBUG_POLL_AND_WAKE ALOGD("%p ~ wake", this);#endif ssize_t nWrite; do { nWrite = write(mWakeWritePipeFd, "W", 1);//就是往管道中寫入了一個「W」字符,用於喚醒,沒有實際的含義。 } while (nWrite == -1 && errno == EINTR); if (nWrite != 1) { if (errno != EAGAIN) { ALOGW("Could not write wake signal, errno=%d", errno); } }}

至此,發送訊息的標準流程算是分析完畢。看到這裡可能還有疑問:為什麼要往管道中寫入一個「W」字符去喚醒 epoll?這就要接著分析一下循環的實現原理了。

3.4 訊息的循環。

前面我們已經分析過,想要正常地使用 Handler 往目標線程發送訊息並得到處理,那麼必須先實例化 Looper 物件,並且讓 Looper 物件呼叫 loop 使它循環地處理訊息佇列中的訊息。Looper.prepare() 然後呼叫 Looper.loop(),使 Looper 循環起來。下面我們來分析 loop 函式的具體實現。

 public static void loop() {

final Looper me = myLooper();//此處就會檢測本線程有沒有呼叫 prepare 方法。 if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) {//在一個 for 循環中,不斷地嘗試去摘取佇列裡的下一條訊息 Message msg = queue.next(); // might block 此處是關鍵,去取得下一個訊息,但是也可能阻塞。 if (msg == null) {//不發生大的異常或者呼叫 Handler 的 quit 方法時,此處不會是 null。 // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); //透過 msg.target 往外派送訊息,msg.target 就是我們發送訊息時用的那個 Handler。 if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }

loop 函式中的整體邏輯很簡單,主要就是先透過 MessageQueue 的 next() 函式去取得下一個 Message(注意可能阻塞),而當正確取到訊息的時候,再呼叫 Handler 的 dispatchMessage 函式做進一步的分發處理。

 public void dispatchMessage(Message msg) {

if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg);//就會呼叫到我們覆寫的 handleMessage 函式。 } }

至此整體流程走完,但我們還需要進一步分析 MessageQueue 的 next 函式,以便更深入地理解為什麼有時候要阻塞、又要怎麼阻塞,這個裡面的循環到底是個什麼邏輯。

MessageQueue 的 next() 函式就是要去 MessageQueue 的訊息鏈條中摘取訊息,然後用於分發處理。對於訊息佇列而言,在摘取訊息時,為了提高效率、減少記憶體和 CPU 的使用,應該考慮很多的技術細節:

a、如果訊息佇列中沒有合適的訊息可以摘取,那麼就要讓它所屬的線程阻塞,而不應該一直循環地做無用的查詢動作。

b、訊息鏈條上面的訊息按觸發時間的順序依次排列,誰先觸發誰在前(這個感覺在發送訊息入隊的時候就已經排序好了)。

c、沒有訊息時阻塞,阻塞的時間最好能精準一點兒,所以應該算出一個合適的時間差,根據還有多長時間首條訊息觸發。

d、有時候外界希望在進入阻塞狀態之前做一些動作(反正這會兒沒訊息處理),這些動作可以稱為 idle 操作,我們要處理這些操作。典型的應用是系統內部很多時候在佇列進入阻塞之前會做一次垃圾回收。

 Message next() {

// Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; //下一個訊息到來的時間(也就是阻塞的時間)。 for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } //第一次 nextPollTimeoutMillis 傳入 0 肯定會立馬返回,不會導致阻塞;傳入一定時間的時候就阻塞這麼長時間;傳入 -1 時,就阻塞直到 epoll 監聽到事件。 nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; //mMessages 就是我們前面發送訊息、插入訊息鏈條時處理的這個,最終把在最前面的訊息賦值給他。 if (msg != null && msg.target == null) {//如果是同步分隔欄,直接去找下一個非同步訊息。這個同步分隔欄其實就是一個 target 為 null 的 Msg。 // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; // 配合 prevMsg = msg 循環查找。 } while (msg != null && !msg.isAsynchronous());// 不是 null,並且不是非同步的訊息的時候就一直循環,直到找到第一個非同步的。 } if (msg != null) {//如果此訊息不為 null,無論是不是同步分隔欄。 if (now < msg.when) { // 那麼如果訊息鏈條中位於頭部的訊息還要等一段時間才到時的話,取時間差即為要堵塞的時間。 // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else {//此時就是已經到時了,該處理這個訊息了。 // Got a message. mBlocked = false;//阻塞置為 false if (prevMsg != null) {//不等於 null 的時候肯定取到的是同步分隔欄後的第一個非同步的訊息。 prevMsg.next = msg.next;//把這個非同步訊息的下一個訊息複製到它的前一個訊息的 next。 } else { mMessages = msg.next;//把當前到時的訊息的下一個賦值給 mMessages,使其成為以後要處理的第一個。 } msg.next = null; if (false) Log.v("MessageQueue", "Returning message: " + msg); return msg;// 返回要處理的這個 } } else { // No more messages. //如果取出來的訊息為 null,也就是沒有訊息要處理了,那麼賦值為 -1,利用 epoll 機制無限阻塞直到下一個訊息到來。 nextPollTimeoutMillis = -1;//這樣下一個循環到前面的 nativePollOnce 會使線程進入阻塞。 } // Process the quit message now that all pending messages have been handled. if (mQuitting) { //主線程不允許退出。 dispose(); //而我們一般也沒有呼叫退出。退出以後就不循環了,程序不卡那了等訊息,這個線程沒有其它的阻塞的話,執行完會退出。 return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. //能走到此處,那就是 msg 為 null 了,暫時沒什麼要處理的,那麼就准備處理一些 idle 操作 if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; //沒有 idle 操作,直接開始下一個循環,並且把阻塞標志置為 true。 } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); //實現 IdleHandler 介面 } catch (Throwable t) { Log.wtf("MessageQueue", "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0;//處理完 handle 操作後,重置一下 // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. //只要佇列中有 Idle Handler 需要處理,那麼在處理完所有 Idle Handler 之後,會強制將 nextPollTimeoutMillis 賦值為 0。 //這主要是考慮到在處理 Idle Handler 時,不知道會耗時多少,雖然處理前已經沒有訊息了,但在此期間訊息佇列極有可能有新的訊息,或者到時了。 nextPollTimeoutMillis = 0;//然後就置 0,讓 nativePollOnce 傳入 0,不等待直接處理一次訊息。 } }

然後就是 nativePollOnce 函式的具體分析以及如何實現阻塞的,它也是 Java native 函式透過 JNI 呼叫到了 android_os_MessageQueue 的 android_os_MessageQueue_nativePollOnce 當中:NativeMessageQueue——>pollOnce——>Looper.pollOnce(time)——>Looper.pollOnce(time,x,x,x)。

 static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jclass clazz,

jlong ptr, jint timeoutMillis) { NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr); nativeMessageQueue->pollOnce(env, timeoutMillis);}

 void NativeMessageQueue::pollOnce(JNIEnv* env, int timeoutMillis) {

mInCallback = true; mLooper->pollOnce(timeoutMillis); mInCallback = false; if (mExceptionObj) { env->Throw(mExceptionObj); env->DeleteLocalRef(mExceptionObj); mExceptionObj = NULL; }}

 int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {

int result = 0; for (;;) { .....//此處省略了一些針對 C++ 層的 Message 資訊的處理。Handler 不僅能處理 Java 層的訊息,還能處理 C++ 層的訊息。 result = pollInner(timeoutMillis);//循環呼叫 pollInner }}

 int Looper::pollInner(int timeoutMillis) {//此方法只分析和 Java 層相關的處理

...... struct epoll_event eventItems[EPOLL_MAX_EVENTS]; //利用 epoll 機制形成阻塞,根據 timeoutMillis 決定阻塞的時長。或者立即返回、或者永久(直到事件觸發)或者特定時間 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis); // No longer idling. mIdling = false; // Acquire lock. mLock.lock(); for (int i = 0; i < eventCount; i++) { // 等到事件以後。 int fd = eventItems[i].data.fd; uint32_t epollEvents = eventItems[i].events; if (fd == mWakeReadPipeFd) { if (epollEvents & EPOLLIN) { //接收到資料,讀 socket awoken(); // 從管道中感知到 EPOLLIN,於是呼叫 awoken() } else { ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents); } } else { ssize_t requestIndex = mRequests.indexOfKey(fd); if (requestIndex >= 0) { int events = 0; if (epollEvents & EPOLLIN) events |= EVENT_INPUT; if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT; if (epollEvents & EPOLLERR) events |= EVENT_ERROR; if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP; pushResponse(events, mRequests.valueAt(requestIndex)); } else { ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is " "no longer registered.", epollEvents, fd); } } } ...... // Release lock. mLock.unlock(); } return result;}

 void Looper::awoken() {

#if DEBUG_POLL_AND_WAKE ALOGD("%p ~ awoken", this);#endif char buffer[16]; ssize_t nRead; do { nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer)); } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));}

可以看出 awoken 函式只是把管道中的資料全部讀取出來,完成清空管道。至此整個取得下一個訊息的處理完畢。

4、總結

兩個線程之間進行通訊,取得目標線程的 Handler 後,透過這個 Handler 向目標線程發送訊息,然後訊息就會被插入到目標線程的訊息佇列中——注意此時的「佇列」不是指佇列資料結構,而是一個概念,就是一個鏈條式的訊息集合。目標線程是一直在 loop 中等待事件的到來,本身並不具備鏈結串列一變動就能感知的功能,但透過管道和 Linux 的 epoll 機制來完成阻塞循環和感知訊息的到來,進而處理分發這個訊息。

個人小知識點理解整理:

1、為什麼不用 notify 和 wait 來實現循環等待了?現在來看的話,在 C++ 層實現了手,Handler 的功能更加強大,並且 native 層也可以利用 Looper.cpp 的函式實現 native 訊息的循環處理,可能效率會更快。

2、Handler.post(Runnable r)。使用這個方法為什麼 Runnable 會執行在 Handler 所屬的線程中?它最終是透過 Handler 的 getPostMessage 方法把 Runnable 封裝到了 Message 的 callback 變數當中,最後插入到了 Handler 所屬的 Looper 的訊息佇列當中,然後循環等待,執行 dispatchMessage 時候會進入到 msg.callback != null 的判斷去執行當前 Runnable 的 run 方法,此時已經到了 Handler 所在的線程中。所以要是主線程的 Handler,那麼就會放到主線程中。下面放一部分源碼:

 public final boolean post(Runnable r)

{ return sendMessageDelayed(getPostMessage(r), 0); }

 private static Message getPostMessage(Runnable r) {

Message m = Message.obtain(); m.callback = r; return m; }

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

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