1. 程式人生 > >Android Handler MessageQueue Looper 訊息機制原理

Android Handler MessageQueue Looper 訊息機制原理

提到Android裡的訊息機制,便會提到Message、Handler、Looper、MessageQueue這四個類,我先簡單介紹以下這4個類 之間的愛恨情仇。 ## Message 訊息的封裝類,裡邊儲存了訊息的詳細資訊,以及要傳遞的資料 ## Handler 主要用在訊息的傳送上,有即時訊息,有延遲訊息,內部還提供了享元模式封裝了訊息物件池,能夠有效的減少重複物件的建立,留更多的記憶體做其他的事, ## Looper 這個類內部持有一個MessageQueue物件,當建立Looper的時候,同時也會建立一個MessageQueue,然後Looper的主要工作就不斷的輪訓MessageQueue,輪到天荒地老的那種 ## MessageQueue 內部持有一個Message物件,採用單項鍊表的形式來維護訊息列隊。並且提供了入隊,出隊的基礎操作 舉個現實中的栗子,Message就相當於包裝好的快遞盒子,Handler就相當於傳送帶,MessageQueue就相當於快遞車,Looper就相當於快遞員,聯想一下,來個快遞盒子,biu丟到傳送帶上,傳送帶很智慧,直接傳送到快遞三輪車裡,然後快遞小哥送一波~,日夜交替,不分晝夜的工作,好傢伙,007工作制 ## 訊息機制的初始化 好,我們把這4個傢伙從頭到位分析一遍,要想使用Android的訊息,首先要建立Looper物件,Android系統已經幫我們在UI執行緒內建立好了一個,我們可以看一下 ```java public final class ActivityThread extends ClientTransactionHandler { /** * The main entry point from zygote. */ public static void main(String[] args) { Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false, startSeq); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); } } ``` `ActivityThread`這個類大家應該不陌生吧,沒錯,他就是我們App的主執行緒管理類,我們看到他呼叫了 `prepareMainLooper` 來初始化,然後 `loop`,天荒地老的那種loop,這個`loop`,我們最後聊 我們看一下Looper內部提供的 `prepareMainLooper` 實現 ```java public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } 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)); } private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } ``` 上邊涉及到了3個方法,我都貼出來了,首先 `quitAllowed` 這個引數代表該Looper是否可以退出,我們主執行緒內的Looper是不允許退出的,所以封裝了 `prepareMainLooper` 方法和 `prepare` 方法已做區分,我們專案中平時用的都是 `prepare` 方法,因為是子執行緒,所以允許退出Looper,大家在子執行緒內用完記得呼叫quit哦~ 這裡我們看Looper內部是通過ThreadLocal維護的Looper物件,也就是說每個執行緒都是相互獨立的。而且Looper做了限制,每個執行緒內部只能存在一個Looper物件,等同於每個執行緒內只能有一個MessageQueue 最後在Looper的構造方法內,建立了一個MessageQueue物件,整個Looper的初始化就結束了 ## 建立訊息 我們準備好了Looper和MessageQueue後,就可以建立訊息啦,接下來我們建立一個訊息吧 ```java //直接new物件,不推薦的方式 Message msg = new Message(); //推薦:內部是一個複用物件池 Message message = handler.obtainMessage(); message.what = 1; message.obj = "hello world"; ``` ## 傳送訊息(入隊) 我們傳送訊息的時候,都是會藉助Handler的sendMessage就可以把訊息傳送到列隊裡了,我們往下看是如何完成的入隊操作吧,首先我們平時都是建立一個Handler,然後呼叫`sendMessage`就可以了 ```java Handler handler = new Handler(); handler.sendMessage(message); ``` 我們先看一下Handler的構造方法 ```java public Handler() { this(null, false); } public Handler(@Nullable Callback callback, boolean async) { //FIND_POTENTIAL_LEAKS一直都是false,所以不用關心這個邏輯 if (FIND_POTENTIAL_LEAKS) { final Class klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } //得到當前執行緒下的Looper物件 mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread " + Thread.currentThread() + " that has not called Looper.prepare()"); } //從Loopper內部獲取一個列隊 mQueue = mLooper.mQueue; // 回撥物件,我們平時寫的時候,一般都是用類整合的方式重寫 handleMessage 方法 mCallback = callback; //標示當前Handler是否支援非同步訊息 mAsynchronous = async; } ``` 其實構造方法很簡單吶,就是獲取Looper物件,然後初始化列隊和回撥物件就完事了,我們繼續看sendMessage然後看訊息的入隊吧 ```java public final boolean sendMessage(@NonNull Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } public boolean sendMessageAtTime(@NonNull 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); } ``` 通過內部的過載方法,一直呼叫到`sendMessageAtTime`方法,在這裡得到Handler內部的`MessageQueue`物件,然後呼叫了 `enqueueMessage` 方法準備入隊 ```java private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg, long uptimeMillis) { msg.target = this; msg.workSourceUid = ThreadLocalWorkSource.getUid(); if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); } ``` 這裡呼叫了MessageQueue的`enqueueMessage`方法真正入隊,我們繼續看一下 ```java 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; //如果連結串列是空的,或者當前訊息的when小於表頭的when的時候,便會重新設定表頭 //這裡可以得知,訊息的順序是按照延遲時間,從小往大排序的 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放到連結串列最後 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; } ``` 通過這個方法,我們瞭解到MessageQueue是通過Message的單鏈結構儲存的,然後每次入隊的時候,都會 通過這個`enqueueMessage`方法向連結串列的最末尾新增資料。 最後我們聊一下Looper下的`loop`方法吧 接下來我們看一下 ```java 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(); // Allow overriding a threshold with a system prop. e.g. // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start' final int thresholdOverride = SystemProperties.getInt("log.looper." + Process.myUid() + "." + Thread.currentThread().getName() + ".slow", 0); boolean slowDeliveryDetected = false; for (;;) { //queue的next會阻塞 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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } // Make sure the observer won't change while processing a transaction. final Observer observer = sObserver; final long traceTag = me.mTraceTag; long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs; if (thresholdOverride > 0) { slowDispatchThresholdMs = thresholdOverride; slowDeliveryThresholdMs = thresholdOverride; } final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0); final boolean logSlowDispatch = (slowDispatchThresholdMs > 0); final boolean needStartTime = logSlowDelivery || logSlowDispatch; final boolean needEndTime = logSlowDispatch; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0; final long dispatchEnd; Object token = null; if (observer != null) { token = observer.messageDispatchStarting(); } long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid); try { //派發訊息,執行回撥handleMessage msg.target.dispatchMessage(msg); if (observer != null) { observer.messageDispatched(token, msg); } dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } catch (Exception exception) { if (observer != null) { observer.dispatchingThrewException(token, msg, exception); } throw exception; } finally { ThreadLocalWorkSource.restore(origWorkSource); if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logSlowDelivery) { if (slowDeliveryDetected) { if ((dispatchStart - msg.when) <= 10) { Slog.w(TAG, "Drained"); slowDeliveryDetected = false; } } else { if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery", msg)) { // Once we write a slow delivery log, suppress until the queue drains. slowDeliveryDetected = true; } } } if (logSlowDispatch) { showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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(); } } ``` Looper內的loop方法別看這麼多,大多數都是日誌相關的處理。其實他就兩件事 第一件事就是從列隊中通過`next`取出Message物件 第二件事就是通過Message物件上繫結的target物件`dispatchMessage`方法,來分發訊息 我們接下來看一下`dispatchMessage`方法,然後在看MessageQueue的`next` ```java public void dispatchMessage(@NonNull Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } ``` 灰常簡單,判斷CallBack物件。然後呼叫handleMessage就完事了,我們的Activity就收到資料了。 接下來我們看看MessageQueue的`next`是怎麼獲取列隊內的訊息的把。 ```java 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) { 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; } } ``` 首先MessageQueue的訊息是用單鏈表的形式儲存,然後next函式做的事情就是死迴圈獲取訊息, 在獲取訊息的時候判斷一下訊息是否符合執行時間,如果不符合執行時間,就進入睡眠狀態等待訊息。 如果符合執行時間就直接返回Message給Looper進行分發,如果Message連結串列都為空。則睡眠時間是-1 代表無休止的睡眠。在無休止睡眠的狀態下,`enqueueMessage`的`nativeWake`方法,會進行一次喚醒,喚醒後`next`函式繼續執行,判斷返回訊息給Looper執行消