概述
- Handler是Android比較基礎,也是非常重要的一個組成部分;整個App運行就是基于消息驅動運行起來的,也可以理解為消費者-生產者模式;
- 原理及實現是相對比較簡單的,主要涉及四個類:Message,Handler,MessageQueue,Looper;Message是消息的載體;Handler是消息的發送者及處理者;MessageQueue是消息隊列,核心操作是入列和出列;Looper從MessageQueue獲取Message并進行分發;
- 消息的執行是異步的;Message分為同步Message和異步Message,可以向MessageQueue中發送同步柵欄,阻止同步Message執行,但是異步Message不受影響;
- Handler可以用于異步/延遲/定時執行,也可用于線程間通信;
- 源碼基于Android-SDK-29;
源碼
Message
- Message是消息的載體,生命周期從發送(獲取Message對象)到處理(Handler處理結束);
- Message是單向鏈式結構;
- Message
public final class Message implements Parcelable { public int what; Handler target; public long when; Runnable callback; public int arg1; public int arg2; public Object obj; Bundle data; }
- what:用來標識什么消息,作用域為對應的Handler,只要Handler能區分所有的what即可;
- target:Message的發送者和處理者;
- when:Message執行的時間,自Android系統啟動以來的時間(不包括系統睡眠時間)為起點;Message不一定正好在when時間執行(可能前面積壓了很多Message),但是肯定不會早于when時間;
- callback:callback也是Message的處理者;
- arg1/arg2/obj:可攜帶的數據;是data的另一種替換方案,不涉及內存分配;
- data:復雜數據或者跨進程攜帶數據;
- 對象池
@UnsupportedAppUsage /*package*/ Message next; //鏈式結構 /** @hide */ public static final Object sPoolSync = new Object(); private static Message sPool; private static int sPoolSize = 0; private static final int MAX_POOL_SIZE = 50;
- Message是生命周期很短(從發送到處理完畢)的對象,并且很多地方都會用到;大量創建生命周期短的對象這種場景下,創建對象本身需要比較耗時,也可能觸發GC,導致系統卡頓不穩定;所以需要對象池;
- Message是單向鏈式結構,對象池只要持有一個Message對象即可;
- 獲取Message對象盡量通過Message.obtain/Handler.obtain方法;源碼中會對sPool加鎖,防止并發調用;
- 跨進程
/** * Optional Messenger where replies to this message can be sent. The * semantics of exactly how this is used are up to the sender and * receiver. */ public Messenger replyTo; /** * Indicates that the uid is not set; * * @hide Only for use within the system server. */ public static final int UID_NONE = -1; /** * Optional field indicating the uid that sent the message. This is * only valid for messages posted by a {@link Messenger}; otherwise, * it will be -1. */ public int sendingUid = UID_NONE; /** * Optional field indicating the uid that caused this message to be enqueued. * * @hide Only for use within the system server. */ public int workSourceUid = UID_NONE;
- 跨進程這塊后面再補;
Handler
- Handler是Message的發送者和處理者;
- 每個Handler對象都綁定到Looper對象,Handler發送Message最終發送到綁定的Looper對象的MessageQueue中;如果創建Handler時未指定了Looper對象,那么就綁定到創建Handler對象時所處的線程的Looper對象;
- 創建Handler對象
public Handler(@Nullable 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 " + Thread.currentThread() + " that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; } public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
- 如果構造函數沒有指定Looper,那么獲取當前線程的Looper對象;構造函數就是為了生成Looper,MessageQueue,Callback(Handler的Callback,不是Message的Callback,類似于Handler.handleMessage方法),Asynchronous(為true時,該Handler發送的都是異步Message);
- 發送消息
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); } 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); }
- 發送Message和Runnable,最終都會調用sendMessageAtTime;Runnable會被封裝為Message對象;sendMessage,sendMessageDelayed通過時間轉化最終都會轉化為sendMessageAtTime;
- Message入列是直接調用MessageQueue.enqueueMessage方法,如果Handler.mAsynchronous為true,則該Handler所有的Message都是異步Message;
public final boolean runWithScissors(@NonNull Runnable r, long timeout) { if (Looper.myLooper() == mLooper) { 調用線程和執行線程是同一個線程時,直接run r.run(); return true; } BlockingRunnable br = new BlockingRunnable(r); return br.postAndWait(this, timeout); }
- 阻塞發送消息:如果Handler綁定的Looper和調用者所在的線程Looper是同一個,直接調用Runnable.run;否則調用者所在的線程阻塞,直到執行結束;
- 發送立即處理消息:postAtFrontOfQueue/sendMessageAtFrontOfQueue方法,設置Message.when為0,Message會排在MessageQueue的最前面,Looper取出的下一個Message就是該Message,所以是立即處理消息;
- 刪除消息
- Handler的刪除消息都會調用MessageQueue對應的方法;
- 處理消息
public void dispatchMessage(@NonNull Message msg) { if (msg.callback != null) { handleCallback(msg); // Runnable轉化的Message } else { if (mCallback != null) { //Handler.Callback優先處理Message,如果返回true,表示處理結束 if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } private static void handleCallback(Message message) { message.callback.run(); } public void handleMessage(@NonNull Message msg) { }
- 如果Message的callback不為null(Runnable轉化的Message),直接調用callback處理;否則,優先Handler.Callback處理,如果返回true,表示處理結束;否則,handleMessage處理;
Looper
- Looper從MessageQueue獲取Message并進行分發;主要功能就是消息循環以及監控;
- Looper是保存在ThreadLocal中,MessageQueue是Looper的實例變量,所以MessageQueue對象也是線程內唯一;
- 線程本地存儲
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); final MessageQueue mQueue; final Thread mThread;
- Looper保存在ThreadLocal中,確保線程內單例;MessageQueue是Looper的成員變量,外部不可創建,所以MessageQueue也是線程內單例;
- 初始化
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(); }
- Looper構造函數中,初始化了MessageQueue,并將Looper保存在ThreadLocal中;
- 初始化必須在對應的線程中調用;
- 默認是可退出的(Looper/MessageQueue);
- 循環
public static void loop() { final Looper me = myLooper(); final MessageQueue queue = me.mQueue; // 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 (;;) { Message msg = queue.next(); // 可阻塞 if (msg == null) { //MessageQueue已退出 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 { 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); } msg.recycleUnchecked(); //Message回收 } }
- 主要代碼就是從MessageQueue中取出要執行的下一個Message(可能阻塞),然后調用Handler.dispatchMessage進行分發;最后回收Message對象;
- 監控
- 在loop方法中,分發Message前后,根根據設置的閾值/Printer/全局Observer,執行對應的Log以及回調;
- 主要用于系統監控,業務層只能設置Printer,但是返回的只有一個拼接好的String,用法有限;
MessageQueue
- MessageQueue是消息隊列,負責Message入列,出列,空閑時間IdleHandler的處理,以及線程的掛起;
- 初始化
MessageQueue(boolean quitAllowed) { mQuitAllowed = quitAllowed; mPtr = nativeInit(); } private native static long nativeInit();
- 初始化Looper對象時,也會初始化MessageQueue,進而在Native層也初始化一個NativeMessageQueue,并在Java層保存起來(mPtr);
- Native層也有消息隊列,和Java層類似,MessageQueue是Native和Java層消息隊列的紐帶;
- 入列
boolean enqueueMessage(Message msg, long when) { 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) { // 插入到頭部 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; //根據when插入到合適位置 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; }
- 可能并發,所以在MessageQueue對象上加鎖;
- 根據Message.when插入到合適位置;
- 如果需要喚醒,則從Native喚醒;
- 出列
Message next() { final long ptr = mPtr; if (ptr == 0) { //消息隊列已經退出 return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { 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) { //同步柵欄,獲取下一個異步Message do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { //頭部Message還未到執行時間 nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { //成功獲取到要分發的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 (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(Java層);
- 調用nativePollOnce,每個迭代優先處理Native層,Native消息處理完,判斷nextPollTimeoutMillis,如果等于0直接返回,如果等于-1進入休眠,如果大于0進入超時休眠;
- 處理Java層,如果頭部Message執行時間已到(包括同步柵欄邏輯)則直接返回Message,否則處理IdleHandler,進入下個迭代;
- 刪除
- 從頭部開始迭代,刪除符合參數的Message;
- IdleHandler
public void addIdleHandler(@NonNull IdleHandler handler) { if (handler == null) { throw new NullPointerException("Can't add a null IdleHandler"); } synchronized (this) { mIdleHandlers.add(handler); } } public void removeIdleHandler(@NonNull IdleHandler handler) { synchronized (this) { mIdleHandlers.remove(handler); } } public boolean isIdle() { synchronized (this) { final long now = SystemClock.uptimeMillis(); return mMessages == null || now < mMessages.when; } }
- IdleHandler用于在消息隊列空閑的時候,執行任務;執行邏輯在next方法中
- IdleHandler.queueIdle:返回true表示保留任務,返回false表示刪除任務只執行一次;
- 同步柵欄
private int postSyncBarrier(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++; //同步柵欄Message(target = null) final Message msg = Message.obtain(); msg.markInUse(); msg.when = when; msg.arg1 = token; //插入同步柵欄Message 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; } } public 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; //定義同步柵欄Message 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; //刪除同步柵欄Message 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); } } }
- 同步柵欄Message,用于拖延同步Message;代碼邏輯在next方法中;
- 添加同步柵欄,將同步柵欄Message插入到合適的位置,該位置之后的Message都被拖延,只有異步消息可以執行,直到該同步柵欄消息被移除;
- 刪除同步柵欄,根據token刪除對應的同步柵欄,如果需要,喚醒線程;
擴展
IdleHandler
- IdleHandler用于在線程空閑時(沒有Message要執行時)執行任務;
- IdleHandler的應用場景
- UI更新后,獲取對應的屬性,通過IdleHandler在空閑時執行,空閑意味著表示UI測量/布局/繪制已經結束;
- Activity中初始化以及加載數據可以在IdleHandler中執行;
- 用于App啟動時間優化;
- 預加載/預處理;
HandlerThread
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
- HandlerThread繼承于Thread,但是多了消息隊列;
- 在 run 方法中調用 Looper.prepare() 初始化消息隊列,然后進入循環隊列;
Messager
- 跨進程通信,待補充;
ANR
- 待補充
總結
- Message是消息的載體(包括Runnable);Handler是消息的發送者(MessageQueue入列)和處理者;Looper負責循環分發消息(MessageQueue出列);MessageQueue負責消息的入列,出列,同步柵欄的處理,IdleHandler的處理;
- MessageQueue是Java層和Native的紐帶;Java層和Native層都有消息隊列,優先處理Native層消息,再處理Java層消息,如果Java層沒有可執行Message,則Native層進入休眠(超時休眠或者一直休眠);入列或者刪除柵欄可喚醒休眠;
存疑
- Messager跨進程通信;
- Native與Java層的消息隊列的交互;