Handler 源代碼理解

1. Handler通過sent或者post方法將目標(biāo)Message推送至MessageQueue。

這里涉及到隊(duì)列優(yōu)先級問題。Handler推送目標(biāo)Message時(shí),會(huì)先通過循環(huán)將目標(biāo)Message的執(zhí)行時(shí)間與MessageQueue里原有Message的執(zhí)行時(shí)間進(jìn)行一一對比,并按照執(zhí)行時(shí)間先后順序?qū)⒛繕?biāo)Message插入MessageQueue。

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) {
            //如果當(dāng)前消息循環(huán)已經(jīng)結(jié)束,直接退出
            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;
            //如果隊(duì)列中沒有消息,或者當(dāng)前進(jìn)入的消息比消息隊(duì)列中的消息等待時(shí)間短,那么就放在消息隊(duì)列的頭部
            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 {
                //判斷喚醒條件,當(dāng)前當(dāng)前消息隊(duì)列頭部消息是屏障消息,且當(dāng)前插入的消息為異步消息
                //且當(dāng)前消息隊(duì)列處于無消息可處理的狀態(tài)
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                //循環(huán)遍歷消息隊(duì)列,把當(dāng)前進(jìn)入的消息放入合適的位置(比較等待時(shí)間)
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                //將消息插入合適的位置
                msg.next = p; 
                prev.next = msg;
            }

            //調(diào)用nativeWake,以觸發(fā)nativePollOnce函數(shù)結(jié)束等待
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
2.Looper通過loop()方法獲取MessageQueue里的Message。

loop()方法會(huì)通過死循環(huán)不斷調(diào)用MessageQueue的next方法來獲取Message,并判斷等待時(shí)間,如果還需要等待則等到相應(yīng)時(shí)間后提取Message。

Message next() {
        
        //如果退出消息消息循環(huán),那么就直接退出
        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();
            }
            
            //執(zhí)行native層消息機(jī)制層,
            //timeOutMillis參數(shù)為超時(shí)等待時(shí)間。如果為-1,則表示無限等待,直到有事件發(fā)生為止。
            //如果值為0,則無需等待立即返回。該方法可能會(huì)阻塞
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                //獲取系統(tǒng)開機(jī)到現(xiàn)在的時(shí)間,如果使用System.currentMillis()會(huì)有誤差,
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;//頭部消息
                
                //判斷是否是柵欄,同時(shí)獲取消息隊(duì)列最近的異步消息
                if (msg != null && msg.target == null) {
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                //獲取消息,判斷等待時(shí)間,如果還需要等待則等待相應(yīng)時(shí)間后喚醒
                if (msg != null) {
                    if (now < msg.when) {//判斷當(dāng)前消息時(shí)間,是不是比當(dāng)前時(shí)間大,計(jì)算時(shí)間差
                        // 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 {
                        // 不需要等待時(shí)間或者等待時(shí)間已經(jīng)到了,那么直接返回該消息
                        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 {
                    //沒有更多的消息了
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                //判斷是否已經(jīng)退出了
                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.
                //獲取空閑時(shí)處理任務(wù)的handler 用于發(fā)現(xiàn)線程何時(shí)阻塞等待更多消息的回調(diào)接口。
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                //如果空閑時(shí)處理任務(wù)的handler個(gè)數(shù)為0,繼續(xù)讓線程阻塞
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }
                //判斷當(dāng)前空閑時(shí)處理任務(wù)的handler是否是為空
                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            //只有第一次迭代的時(shí)候,才會(huì)執(zhí)行下面代碼
            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);
                }
                //如果不保存空閑任務(wù),執(zhí)行完成后直接刪除
                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // 重置空閑的handler個(gè)數(shù),因?yàn)椴恍枰貜?fù)執(zhí)行
            pendingIdleHandlerCount = 0;
            
            //當(dāng)執(zhí)行完空閑的handler的時(shí)候,新的native消息可能會(huì)進(jìn)入,所以喚醒Native消息機(jī)制層
            nextPollTimeoutMillis = 0;
        }
    }
Looper取出Message后會(huì)執(zhí)行message.target.dispatchMessage()方法,即handler的dispatchMessage()方法,并在該方法里執(zhí)行handleMessage。至此,Handler的一個(gè)消息循環(huán)結(jié)束。

參考文檔:
http://www.itdecent.cn/p/219701879fe4
http://www.itdecent.cn/p/3d8f7ec1017a

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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