Android IdleHandler 詳解

介紹

IdleHandlerMessageQueue 內(nèi)定義的一個(gè)接口,一般可用于做性能優(yōu)化。當(dāng)消息隊(duì)列內(nèi)沒(méi)有需要立即執(zhí)行的 message 時(shí),會(huì)主動(dòng)觸發(fā) IdleHandlerqueueIdle 方法。返回值為 false,即只會(huì)執(zhí)行一次;返回值為 true,即每次當(dāng)消息隊(duì)列內(nèi)沒(méi)有需要立即執(zhí)行的消息時(shí),都會(huì)觸發(fā)該方法。

public final class MessageQueue {
    public static interface IdleHandler {
        boolean queueIdle();
    }
}

使用方式

通過(guò)獲取 looper 對(duì)應(yīng)的 MessageQueue 隊(duì)列注冊(cè)監(jiān)聽(tīng)。

Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
    @Override
    public boolean queueIdle() {
        // doSomething()
        return false;
    }
});

源碼解析

IdleHandler 的執(zhí)行源碼很短。

Message next() {
    // 隱藏?zé)o關(guān)代碼...
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (; ; ) {
        // 隱藏?zé)o關(guān)代碼...
        // 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;
}
  1. MessageQueuenext 方法的 for 死循環(huán)內(nèi),獲取 mIdleHandlers 的數(shù)量 pendingIdleHandlerCount;
  2. 通過(guò) mMessages == null || now < mMessages.when 判斷當(dāng)前消息隊(duì)列為空或者目前沒(méi)有需要執(zhí)行的消息時(shí),給 pendingIdleHandlerCount 賦值;
  3. 當(dāng)數(shù)量大于 0,遍歷取出數(shù)組內(nèi)的 IdleHandler,執(zhí)行 queueIdle()
  4. 返回值為 false 時(shí),主動(dòng)移除監(jiān)聽(tīng) mIdleHandlers.remove(idler);

使用場(chǎng)景

  1. 如果啟動(dòng)的 Activity、FragmentDialog 內(nèi)含有大量數(shù)據(jù)和視圖的加載,導(dǎo)致首次打開(kāi)時(shí)動(dòng)畫切換卡頓或者一瞬間白屏,可將部分加載邏輯放到 queueIdle() 內(nèi)處理。例如引導(dǎo)圖的加載和彈窗提示等;
  2. 系統(tǒng)源碼中 ActivityThreadGcIdler,在某些場(chǎng)景等待消息隊(duì)列暫時(shí)空閑時(shí)會(huì)嘗試執(zhí)行 GC 操作;
  3. 系統(tǒng)源碼中 ActivityThreadIdler,在 handleResumeActivity() 方法內(nèi)會(huì)注冊(cè) Idler(),等待 handleResumeActivity 后視圖繪制完成,消息隊(duì)列暫時(shí)空閑時(shí)再調(diào)用 AMSactivityIdle 方法,檢查頁(yè)面的生命周期狀態(tài),觸發(fā) activitystop 生命周期等。
    這也是為什么我們 BActivity 跳轉(zhuǎn) CActivity 時(shí),BActivity 生命周期的 onStop() 會(huì)在 CActivityonResume() 后。
  4. 一些第三方框架 GlideLeakCanary 等也使用到 IdleHandler,感興趣的朋友可以看看源碼;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • use for 相信于此,絕大多數(shù)同學(xué)都會(huì)回答消息機(jī)制是android 為了線程間通信而引入的工具??梢暂p松的將一...
    漫步_蝸牛閱讀 530評(píng)論 0 1
  • Handler是什么 先來(lái)看官方文檔對(duì)Handler的描述A Handler allows you to send...
    ywy_袁滾滾閱讀 943評(píng)論 0 3
  • 在Android系統(tǒng)中,Handler機(jī)制應(yīng)用較廣,尤其是在App層面,基本每個(gè)App都會(huì)用到。使用的場(chǎng)景主要是向...
    路路人王閱讀 873評(píng)論 0 49
  • 概述 Handler是Android比較基礎(chǔ),也是非常重要的一個(gè)組成部分;整個(gè)App運(yùn)行就是基于消息驅(qū)動(dòng)運(yùn)行起來(lái)的...
    CodeMagic閱讀 476評(píng)論 0 0
  • 首先提出幾個(gè)問(wèn)題,如果對(duì)以下幾個(gè)問(wèn)題都有深刻的了解,那么就不再建議看本文,直接略過(guò) 1.我們常說(shuō)的主線程指的是啥?...
    蘿卜小青菜丶閱讀 404評(píng)論 0 0

友情鏈接更多精彩內(nèi)容