Handler機(jī)制

消息機(jī)制

Java層

1.Looper構(gòu)建了消息隊(duì)列MessageQueue
2.Message的成員target關(guān)聯(lián)Handler
3.Handler的成員mQueue關(guān)聯(lián)MessageQueue,成員mLooper關(guān)聯(lián)Looper
4.MessageQueue的成員mMessages關(guān)聯(lián)Message

我們使用Handler時(shí)都是先要調(diào)Looper的prepare方法浇垦,用于創(chuàng)建Looper和MessageQueue,主線程直接使用Handler是因?yàn)樵谙到y(tǒng)已經(jīng)提前給我們創(chuàng)建好了主線程的Looper和MessageQueue
創(chuàng)建App進(jìn)程后會(huì)調(diào)用ActivityThread的main()方法

public static void main(String[] args) {
        ···
        Looper.prepareMainLooper();
        ····
        Looper.loop();
    }

1荣挨,創(chuàng)建主線程Looper
2男韧,為主線程Handler賦值
3朴摊,Looper.looper啟動(dòng)循環(huán)

Looper的prepare()

Looper.prepareMainLooper

   public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

prepare(false)這里的prepare傳的是false,我們自己創(chuàng)建的線程調(diào)用Looper.prepare()傳遞的是true表示可以退出
sMainLooper為全局主線程Looper賦值

public static void prepare() {
    prepare(true);
}
private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {  /* 如果消費(fèi)者線程已有Looper綁定了,則拋出異常 */
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed)); /* 創(chuàng)建Looper,并綁定到消費(fèi)者線程 */
}

如果Looper.prepare只能調(diào)用一次此虑,如果多次調(diào)用會(huì)拋異常
Looper創(chuàng)建后會(huì)存儲(chǔ)在ThreadLocal中甚纲,ThreadLocal可以保證線程是唯一的

Looper的構(gòu)造函數(shù)

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed); //創(chuàng)建消息隊(duì)列
    mThread = Thread.currentThread();       //記錄消費(fèi)者線程
}

Looper的loop()

public static void loop() {
......
    for (;;) {
        Message msg = queue.next(); //消息隊(duì)列出隊(duì)得到Message事務(wù)
        if (msg == null) {
            return;
    }
    msg.target.dispatchMessage(msg);//執(zhí)行具體事務(wù)
......
}

MessageQueue.next

 Message next() {
        ···
        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) {
                    // 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.
                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,nativePollOnce 如果無消息讓消費(fèi)者線程進(jìn)入休眠狀態(tài)
2朦前,如果設(shè)置消息屏障取出異步消息
3介杆,檢測(cè)消息時(shí)間是否到達(dá),到達(dá)取出消息韭寸,未到達(dá)設(shè)置超時(shí)時(shí)間(目標(biāo)時(shí)間 - 當(dāng)前時(shí)間)
4春哨,未到達(dá),設(shè)置超時(shí)時(shí)間恩伺,消費(fèi)者線程進(jìn)入休眠
5赴背,執(zhí)行IdelHanlder

msg.target.dispatchMessage(msg)

 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

1,先處理Message CallBack
2晶渠,Handler的Callback
3凰荚,處理handleMessage

發(fā)送消息

Hanlder.sendMessage(),最終會(huì)調(diào)用MessageQueue的enqueueMessage

  boolean enqueueMessage(Message msg, long when) {      
          ···
            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 {
                // 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;
    }

1乱陡,如果隊(duì)列為空直接插入節(jié)點(diǎn)
2浇揩,隊(duì)列不為空,按時(shí)間排序插入
3憨颠,線程休眠胳徽,插入消息為屏障,插入消息是異步消息并且在第一位爽彤,需要喚醒線程

Native層

Looper.prepare()

sp<Looper> Looper::prepare(int opts) {
......
    /* 獲取當(dāng)前消費(fèi)者線程線程綁定的Looper對(duì)象
     * 由于這里首次調(diào)用prepare,還未綁定Looper,因此返回空 
     */
    sp<Looper> looper = Looper::getForThread();
    if (looper == NULL) {
    /* 創(chuàng)建Looper對(duì)象(見1.2),然后綁定到當(dāng)前消費(fèi)者線程中 */
        looper = new Looper(allowNonCallbacks);
        Looper::setForThread(looper);
    }

    return looper;
......
}

在Looper的構(gòu)造函數(shù)
1养盗,創(chuàng)建了eventfd
2,創(chuàng)建epoll文件描述符适篙,用于監(jiān)聽eventfd
Looper.pollOnce
1往核,消費(fèi)者線程調(diào)用epoll.wait檢測(cè)是否有消息就緒,如果沒有休眠
2嚷节,當(dāng)fd就緒聂儒,消費(fèi)者線程被喚醒

MessageQueue
構(gòu)造函數(shù)中會(huì)創(chuàng)建Looper
?1.Looper(Java)啟動(dòng)消息循環(huán),先處理Looper(Native)事務(wù),然后再處理Looper(Java)事務(wù)
?2.Looper(Native)和Looper(Java)均無事務(wù)處理時(shí),消費(fèi)者線程會(huì)進(jìn)入超時(shí)休眠狀態(tài),等待事務(wù)就緒時(shí)喚醒

參考
Android P源碼分析之Looper(Native)
Android P源碼分析之Handler(JAVA)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市硫痰,隨后出現(xiàn)的幾起案子衩婚,更是在濱河造成了極大的恐慌,老刑警劉巖效斑,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件非春,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)奇昙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門护侮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人储耐,你說我怎么就攤上這事羊初。” “怎么了弧岳?”我有些...
    開封第一講書人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵凳忙,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我禽炬,道長(zhǎng)涧卵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任腹尖,我火速辦了婚禮柳恐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘热幔。我一直安慰自己乐设,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開白布绎巨。 她就那樣靜靜地躺著近尚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪场勤。 梳的紋絲不亂的頭發(fā)上戈锻,一...
    開封第一講書人閱讀 51,541評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音和媳,去河邊找鬼格遭。 笑死,一個(gè)胖子當(dāng)著我的面吹牛留瞳,可吹牛的內(nèi)容都是我干的拒迅。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼她倘,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼璧微!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起硬梁,我...
    開封第一講書人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤前硫,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后靶溜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年罩息,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了嗤详。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瓷炮,死狀恐怖葱色,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情娘香,我是刑警寧澤苍狰,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站烘绽,受9級(jí)特大地震影響淋昭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜安接,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一翔忽、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧盏檐,春花似錦歇式、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至硫豆,卻和暖如春龙巨,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背够庙。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工恭应, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人耘眨。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓昼榛,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親剔难。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胆屿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355