介紹
在android的MessageQueue中有一個static的接口IdleHandler,這個接口用於在MessageQueue中沒有可處理的Message的時候回調,這樣就能夠在UI線程中處理完全部的view事務以後,回調一些額外的操做而不會block UI線程。java
public static interface IdleHandler { /** * Called when the message queue has run out of messages and will now * wait for more. Return true to keep your idle handler active, false * to have it removed. This may be called if there are still messages * pending in the queue, but they are all scheduled to be dispatched * after the current time. */ boolean queueIdle(); }
使用
接口很簡單,只有一個queueIdle方法,用於在進入Idle的時候執行額外的操做,返回值是ture的話,執行完queueIdle方法以後會保留這個IdleHandler,反之則刪除這個IdleHandler。android
使用起來也很簡單。app
mHandler.getLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() { @Override public boolean queueIdle() { Log.e(TAG, "----I am idle"); return false; } });
源碼淺析
MessageQueue的Message都是在next方法中執行的,直接看next方法async
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. //第一次進入,而且msg爲null或者是當前的msg schedule到後面執行 if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { //獲取當前IdleHandler的數量 pendingIdleHandlerCount = mIdleHandlers.size(); } //沒有須要處理的idleHandler,退出 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)]; } //用將全部的idleHandler存入mPendingIdleHandlers 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); } //根據返回值,選擇是否remove這個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; } }
這段代碼能夠分爲兩部分來看,第一部分用於從MessageQueue中取出可用的message,第二部分用於處理IdleHandler。咱們直接從第二部分來看,首先會對當前的msg做一個判斷,若是message爲null或者是schedule到未來執行,那麼就開始準備執行IdleHandler。全部的idleHandler放在mIdleHandlers
中,將這些idleHandler轉存到mPendingIdleHandlers
,接下來就是迭代處理這些IdleHandler,若是返回值是false,就把這個idleHandler從mIdleHandlers
中remove掉。ide