Android基礎-Handler原始碼
最近深感對基礎知識不夠紮實, 所以回頭看一下Handler
的原始碼. 首先, 我們先從他的使用作為入口來
Handler的使用
先看下, 幾種通過Handler傳送訊息的用法, 一共有四種, 當然最終呼叫的還是Handler#sendMessageDelayed(Message msg, long delayMillis)
, 這個我們放在後面去解析.
private fun sendHandler(){ // 1 MyHandler().obtainMessage(1).sendToTarget() // 2 val msg = Message() msg.what = 2 MyHandler().sendMessage(msg) // 3 MyHandler().post { Log.e(MainActivity::class.java.canonicalName, "3") } // 4 val callback = Handler.Callback { Log.e(MainActivity::class.java.canonicalName, it.what.toString()) true } val msg2 = Message() msg2.what=4 MyHandler(callback).sendMessage(msg2) }
然後是他通用的訊息接收處理
// kotlin內部類預設為靜態類 private class MyHandler: Handler { constructor() constructor(callback: Callback) override fun handleMessage(msg: Message?) { super.handleMessage(msg) Log.e(MainActivity::class.java.canonicalName, msg?.what.toString()) } }
Handler構造
要了解Handler
, 我們首先看他的建構函式,Handler
的構造, 實際分為兩種, 一種是傳入Looper
, 一種是直接使用當前執行緒的Looper
, 可以看到, 主要就是通過預設當前執行緒Looper或者是提供的Looper獲取messageQueue
物件.
public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> 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 that has not called Looper.prepare()"); } // 獲取looper持有的messageQueue mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; } // 使用提供的Looper物件 public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
當我們在子執行緒內直接傳送訊息, 會丟擲異常, 具體我們可以從Looper#myLooper()
開始看
/** * Return the Looper object associated with the current thread.Returns * null if the calling thread is not associated with a Looper. */ public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
ThreadLocal
這裡不細說, 反正知道他是每個執行緒獨有的儲存空間就行了.可以看到, looper是每個執行緒不共享的記憶體物件, 它儲存在ThreadLocal內, 而在Looper#prepare
會進行Looper的例項化, 和儲存在threadLocal內
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(); }
傳送訊息
Handler傳送訊息最終都會走到Handler#sendMessageDelayed
方法, 會發現他最終呼叫的是MessageQueue#enqueueMessage(Message msg, long when)
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) { 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; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
MessageQueue
雖然說是訊息佇列, 但是實際實現佇列機制是依靠的Message
的資料結構,每一個Message
都會通過它內部的next
欄位指向另外一個Message
, 最終實現了單向列表的資料結構, 而MessageQueue
內部的mMessages
就是佇列頭的訊息物件, 具體可以看下, 插入訊息時候的方法體
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 (mQuittying) { 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. // 將當前訊息置於列表頂 // 當前訊息的下一條訊息指向之前的mMessages 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; }
訊息處理
關於訊息的處理, 我們又要回頭去看Looper
, 關於MessageQueue
它主要做了兩個事情, 從Handler
那邊接收Message
做佇列託管, 然後將符合條件的Message
返回給Looper
, 具體我們可以看下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; // 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 (;;) { // 1. 獲取message Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // 2. handler的分發處理 msg.target.dispatchMessage(msg); ... // 3. 訊息的回收 msg.recycleUnchecked(); } }
刪除了一些無關的程式碼, 我們看下核心流程,Looper#loop
就一直不斷迴圈的在做三件事:
-
拿取
MessageQueue
中的Message
-
呼叫
Message
持有的handler的分發處理事件 -
回收已處理掉的
Message
我們來看下MessageQueue
給到Looper
怎麼樣的Message
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; // 當頭部訊息的target(攜帶handler)為空的情況下 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. // 指向下一條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(); // 返回當前的message 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. // 當佇列空閒(頭部訊息為空或者頭部訊息還未到時候執行), 並且沒有閒置handler的時候 if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run.Loop and wait some more. // 當沒有閒置handler需要執行的時候 mBlocked = true; continue; } // 如果閒置handlers陣列為空 if (mPendingIdleHandlers == null) { // 初始化, 閒置的handlers最大數為4 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集合的第一個handler元素 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); } // 假設空閒回撥處理不保留這個閒置處理, 則移除對應的idleHandler 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#when
回頭看Handler#dispatchMessage(Message msg)
, 可以瞭解到handler處理事件的優先順序
public void dispatchMessage(Message msg) { // msg.callback通過handler.post傳入的runnable if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { // mCallback是通過Handler的建構函式傳入 if (mCallback.handleMessage(msg)) { return; } } // 最後才是Message傳入的處理, 一般是繼承Handler, 重寫handleMessage方法 handleMessage(msg); } }
關於Message的重複利用
主流程基本分析完畢, 我們現在再回頭看使用API, 一般的業務場景, 我們用到比較多的可能是自己新建包裝一個Message
, 通過Handler來發送. 那麼Handler#obtainMessage()
做了什麼呢, 為什麼通過這個自己可以不用再新建一個Message了. 我們看API調取, 會發現他內部呼叫到了Message#obtain()
, 而最終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(); }
可以看到, 當sPool
物件不為空的時候, 是複用了這個物件的記憶體空間.那麼sPool
又是什麼時候被賦值的呢
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) { // MAX_POOL_SIZE == 50 if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this; sPoolSize++; } } }
這個方法是不是有點眼熟, 就是前面分析Looper#loop()
時候, 當訊息處理完以後, 訊息回收呼叫到的, 可以看到sPool作為需要被回收的物件, 當訊息處理完後, 當前訊息進入當前回收佇列中, 這樣可以達到Message
的複用作用