標籤:
概覽
Android訊息機制是Android作業系統中比較重要的一塊。具體使用方法在這裡不再闡述,可以參考Android的官方開發文檔。
訊息機制的主要用途有兩方面:
1、線程之間的通訊。比如在子線程中想更新UI,就通過發送更新訊息到UI線程中來實現。
2、任務順延強制。比如30秒後執行重新整理任務等。
訊息機制啟動並執行大概如下:
一個線程中只能有一個Looper對象,一個Looper對象中持有一個訊息佇列,一個訊息佇列中維護多個訊息對象,用一個Looper可以建立多個Handler對象,Handler對象用來發送訊息到訊息佇列中、和處理Looper分發給自己的訊息(也就是自己之前發送的那些訊息),這些Handler對象可以跨線程運行,但是最終訊息的處理,都是在建立該Handler的線程中運行。
分析
在熟悉了基本用法之後,有必要深入探索一下。
邏輯分析
Android訊息機制的framework層主要圍繞Handler、Looper、Message、MessageQueue這四個對象來操作。訊息機制主要是對訊息進行產生、發送、儲存、分發、處理等操作。
Message:
該類代表的是訊息機制中的訊息對象。是在訊息機制中被建立,用來傳遞資料以及操作的對象,也負責維護訊息對象緩衝池。
Message對象中主要有以下幾個屬性:
what:訊息類型。
arg1、arg2、obj、data:該訊息的資料域
when:該訊息應該被處理的時間,該欄位的值為SystemClock.uptimeMillis()。當該欄位值為0時,說明該訊息需要被放置到訊息佇列的首部。
target:發送和處理該訊息的Handler對象。
next:對象池中該訊息的下一個訊息。
Message對象中,主要維護了一個Message對象池,因為系統中會頻繁的使用到Message對象,所以用對象池的方式來減少頻繁建立對象帶來的開支。Message對象池使用單鏈表實現。最大數量限制為50。所以官方推薦我們通過對象池來擷取Message對象。
特別注意的是,我們平常使用的都是普通的Message對象,也就是同步的Message對象。其實還有兩種特殊的Message對象,目前很少被使用到,但也有必要瞭解一下。
第一個是同步的障礙訊息(Barrier Message),該訊息的作用就是,如果該訊息到達訊息佇列的首部,則訊息佇列中其他的同步訊息就會被阻塞,不能被處理。障礙訊息的特徵是target==null&&arg1==barrierToken
第二個是非同步訊息,非同步訊息不會被上面所說的障礙訊息影響。通過Message對象的setAsynchronous(boolean async)方法來設定一個訊息為非同步訊息。
MessageQueue:
該類代表的是訊息機制中的訊息佇列。它主要就是維護一個安全執行緒的訊息佇列,提供訊息的入隊、刪除、以及阻塞方式的輪詢取出等操作。
Looper:
該類代表的是訊息機制中的訊息分發器。 有了訊息,有了訊息佇列,還缺少處理訊息分發機制的對象,Looper就是處理訊息分發機制的對象。它會把每個Message發送到正確的處理對象上進行處理。如果一個Looper開始工作後,一直沒有訊息處理的話,那麼該線程就會被阻塞。在非UI線程中,這時候應該監聽當前MessageQueue的Idle事件,如果當前有Idle事件,則應該退出當前的訊息迴圈,然後結束該線程,釋放相應的資源。
Handler:
該類代表的是訊息機制中的訊息發送和處理器。有了訊息、訊息佇列、訊息分發機制,還缺少的就是訊息投遞和訊息處理。Handler就是用來做訊息投遞和訊息處理的。Handler事件處理機制採用一種按自由度從高到低的優先順序進行訊息的處理,正常情況下,一個Handler對象可以設定一個callback屬性,一個Handler對象可以操作多個Message對象,從某種程度上來說,建立一個Message對象比給一個Handler對象設定callback屬性來的自由,而給一個Handler對象設定callback屬性比衍生一個Handler子類來的自由,所以訊息處理優先順序為Message>Handler.callback.Handler.handleMessage()。
程式碼分析
重要部分的原始碼解析,原始碼基於sdk 23。
Message:
普通的訊息對象,包含了訊息類型、資料、行為。內部包含了一個用單鏈表實現的對象池,最大數量為50,為了避免頻繁的建立對象帶來的開銷。
1、從對象池中擷取Message對象。
原始碼:
public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; m.flags = 0; // clear in-use flag sPoolSize--; return m; } } return new Message(); }
虛擬碼:
public static Message obtain() { synchronized (sPoolSync) { if (對象池不為空白) { 從單鏈表實現的對象池中取出一個對象(從鏈表頭擷取); 清空該對象標誌位(在使用中、非同步等); 修正對象池大小; return 取出的訊息對象; } } return 建立訊息對象; }
2、返回Message對象到對象池
原始碼:
void recycleUnchecked() { // Mark the message as in use while it remains in the recycled object pool. // Clear out all other details. flags = FLAG_IN_USE; what = 0; arg1 = 0; arg2 = 0; obj = null; replyTo = null; sendingUid = -1; when = 0; target = null; callback = null; data = null; synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this; sPoolSize++; } } }
虛擬碼:
void recycleUnchecked() { 標誌為正在使用中; 清空當前對象的其他資料; synchronized (sPoolSync) { if (對象池沒容量有達到上限) { 在單鏈表表頭插入該對象; 修正對象池大小; } } }
Looper:
使用ThreadLocal來實現線程範圍的控制,每個線程最多有一個Looper對象,內部持有一個MessageQueue的引用。
1、初始化一個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)); }
虛擬碼:
private static void prepare(boolean quitAllowed) { if (當前線程中已經有了一個Looper對象) { throw new RuntimeException("一個線程只能建立一個Looper對象"); } 重新執行個體化一個可以退出的Looper; 把該Looper對象和當前線程關聯起來; }
2、Looper開始工作
原始碼:
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; // 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 (;;) { Message msg = queue.next(); // might block if (msg == 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); 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(); } }
虛擬碼:
public static void loop() { 擷取當前線程的Looper對象; if (當前線程沒有Looper對象) { throw new RuntimeException("沒有Looper; Looper.prepare() 沒有在當前線程被調用過"); } 擷取該Looper對象關聯的MessageQueue; 清除IPC身份標誌; for (;;) { 從MessageQueue中擷取一個Message,如果當前MessageQueue沒有訊息,就會阻塞; if (沒有取到訊息) { // 沒有訊息意味著訊息佇列退出了. return; } 列印日誌; 調用當前Message對象的target來處理訊息,也就是發送該Message的Handler對象; 列印日誌; 擷取新的IPC身份標識; if (IPC身份標識改變了) { 列印警告資訊; 回收該訊息,放入到Message對象池中; } }
Handler:
負責訊息的發送、定時發送、延遲發送、訊息處理等動作。
1、事件處理
原始碼:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
虛擬碼:
public void dispatchMessage(Message msg) { if (該訊息的callback屬性不為空白) { 運行該訊息的callback對象的run()方法; } else { if (當前Handler對象的mCallback屬性不為空白) { if (mCallback對象成功處理了訊息) { return; } } Handler內部處理該訊息; } }
MessageQueue:
使用單鏈表的方式維護一個訊息佇列,提高頻繁插入刪除訊息等操作的效能,該鏈表用訊息的when欄位進行排序,先被處理的訊息排在鏈表前部。內部的阻塞輪詢和喚醒等操作,使用JNI來實現。
1、Message對象的入隊操作
原始碼:
boolean enqueueMessage(Message msg, long when) { 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(TAG, e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don‘t have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; }
虛擬碼:
boolean enqueueMessage(Message msg, long when) { if (該訊息沒有target) { throw new IllegalArgumentException("Message對象必須要有一個target"); } if (該訊息正在被使用) { throw new IllegalStateException(msg + " 該訊息正在使用中"); } synchronized (this) { if (訊息佇列退出了) { 列印警告資訊; 回收該訊息,返回到Message對象池; return false; } 設定該訊息為正在使用中; 設定訊息將要被處理的時間; Message p = mMessages; boolean needWake; if (msg隊列為空白 || 該訊息對象請求放到隊首 || 執行時間先於當前隊首msg的執行時間(當前隊列中全是delay msg)) { 把當前msg添加到msg隊列首部; 如果阻塞了,設定為需要被喚醒; } else { if (阻塞了 && 隊首是barrier && 當前msg是非同步msg) { 設定為需要被喚醒 } for (;;) { 根據msg.when的先後,找到合適的插入位置,先執行的在隊列前面; if (需要喚醒 && 插入位置之前有非同步訊息) { 不需要喚醒; } } 插入到合適的位置; } if (需要喚醒) { 調用native方法進行本地喚醒; } } return true; }
2、查詢待處理訊息
原始碼:
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(); } 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; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != 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; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // 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. 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; } 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(); } catch (Throwable t) { Log.wtf(TAG, "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; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }
虛擬碼:
Message next() { if (訊息佇列退出了) { return null; } 把Idle事件的次數標記為第一次; 下一次輪詢的等待(阻塞)時間設為0; for (;;) { if (下一次輪詢需要阻塞) { 清楚Binder的pending command,用來釋放資源; } 使用當前的設定輪詢阻塞時間去做一次native的輪詢,如果阻塞時間大於0,則會阻塞,直到取到訊息為止; synchronized (this) { if (訊息佇列首部為barrier訊息) { 取出第一個非同步訊息; } if (查詢到滿足條件的訊息) { if (還沒到該訊息的執行時間) { 設定下一次輪詢的阻塞時間為msg.when - now,最大不超過Integer.MAX_VALUE; } else { 阻塞標識設定為false; 取出該訊息,重新導向鏈表頭; 標記該訊息為在使用中; return 該訊息; } } else { 沒有訊息,設定下一次輪詢阻塞時間為-1,不阻塞; } if (訊息佇列退出了) { 釋放資源; 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. if (第一次Idle事件) { 計算Idle監聽器數量; } if (沒有Idle監聽器) { 阻塞標識設定為true; continue; } 產生Idle監聽對象; } for (int i = 0; i < pendingIdleHandlerCount; i++) { 通知Idle事件的監聽對象,根據標識來確定這些監聽器是否繼續監聽。 } 設定Idle事件的標識為不是第一次; 調用了Idle監聽器之後,可能有新的訊息進入隊列,所以下一次輪詢阻塞時間設定為0; } }
Android訊息機制探索(Handler,Looper,Message,MessageQueue)