Android中的消息機(jī)制(MessageQueue, Looper, Handler)總結(jié)

背景

最近在使用Handler输钩,想搞清楚他的原理营罢,在網(wǎng)上看了好幾篇文章都看的云里霧里的赏陵,直到看到了任玉剛老師的文章我才有了“啊,原來(lái)是這樣饲漾!”的感覺(jué)蝙搔。他的博客一再提分享精神,對(duì)我感觸很大考传。所以決定把自己對(duì)Handler的想法給大家分享一下吃型, 哪里有不對(duì)的地方聯(lián)系我, 我們一起探討一起進(jìn)步僚楞。

前言

我們大家都知道Android為了滿足線程間的通信為我們提供了Looper和Handler勤晚。相信大家也都知道Handler怎么使用,可是Handler為什么要這么用呢泉褐?什么原理呢兴枯?今天不討論他怎么用,我們來(lái)分析一下他的工作流程。如果堅(jiān)持讀到最后夕膀,相信你一定會(huì)有所收獲的(ps:哪位小伙伴不了解用法可以留言,空閑下來(lái)我會(huì)寫(xiě)一篇用法供你了解)

正文

消息機(jī)制的工作流程:

我們先來(lái)看一下他的流程圖

消息機(jī)制

????最開(kāi)始先由執(zhí)行任務(wù)的線程通過(guò)Handler發(fā)送消息即去向MessageQueu(消息隊(duì)列)去插入一條消息具壮,然后Looper從MessageQueue中不斷地循環(huán)來(lái)取出消息攘已,經(jīng)由Looper處理最終將他交給了Hanlder,這樣最終就由Handler所在的線程來(lái)處理這條消息了看幼。想必大家還是不太清楚搏熄,讓我們接下來(lái)詳細(xì)的分析一下每個(gè)步驟鞋囊。

MessageQueue(消息隊(duì)列)

我們先來(lái)看一下他的源碼

public final class 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) {
            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) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                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;
    }
                  .....
     Message next() {

        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;
                }
                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);
            }

            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);
                    }
                }
            }
            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }
}

代碼比較長(zhǎng)夯缺,大家不用深究棵里,看代碼我們不難發(fā)現(xiàn)實(shí)際上他就是一個(gè)鏈表典蝌。通過(guò)enqueueMessage()方法來(lái)插入消息昔脯,通過(guò)next()來(lái)返回并移除消息,這就是MessageQueue的工作原理,讓我們先記住這兩個(gè)方法的名字。

Looper

我們還是先來(lái)看一下代碼在做解釋

public final class Looper {
              ......
   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));
    }
}

先來(lái)看一下他的prepare()方法脯倒,首先他先做了一個(gè)判斷郁岩,如果已經(jīng)存在了Looper他就會(huì)拋出

throw new RuntimeException("Only one Looper may be created per thread");

這也就是為什么一個(gè)線程只能存在一個(gè)Looper的原因。讓我們繼續(xù)向下看

public final class Looper {
              ......
   public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {

            Message msg = queue.next(); // 注意這里H绲稹1尽!

            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);  //注意這里!S环小歇终!

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }


}

從代碼我們可以看出內(nèi)部就是一個(gè)無(wú)限循環(huán),不斷地調(diào)用MessageQueue的next()方法來(lái)取出消息逼龟,沒(méi)錯(cuò)就是之前讓你記住MessageQueue中的兩個(gè)方法之一评凝。最后執(zhí)行這行代碼

msg.target.dispatchMessage(msg); //注意這里!O俾伞奕短!

這里的msg.target就是我們所說(shuō)的Handler(),沒(méi)錯(cuò),就是在這里將我們的消息最終交給了Handler匀钧。也許你會(huì)說(shuō):你說(shuō)是就是啊我們?cè)趺粗滥阌袥](méi)有騙我翎碑。

public final class Message implements Parcelable {
            ........
            Handler target;
            .......
}

這回你信了吧。這里L(fēng)ooper你應(yīng)該明白了之斯,經(jīng)過(guò)Looper的處理最終將消息交給了我們的Handler日杈,讓我們繼續(xù)看Handler。

Handler

我們先來(lái)看他的sendMessage().

public final boolean sendMessage(Message msg){    
        return sendMessageDelayed(msg, 0);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

 public boolean sendMessageAtTime(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);//注意這里S铀ⅰ4镆!
    }

經(jīng)過(guò)sendMessage的層層調(diào)用项乒,最后我們發(fā)現(xiàn)他調(diào)用了enqueueMessage(),也就是最開(kāi)始我們記住的兩個(gè)方法之一梁沧,就是向MessageQueue中插入消息檀何。這也就是我們的發(fā)送階段。我們還記得Looper最后調(diào)用了Handler的dispatchMessage()廷支,他內(nèi)部是什么機(jī)制呢频鉴,讓我們來(lái)看一下。

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);//注意這里A蹬摹6饪住!
        }
    }

到了這里我相信大家一定不會(huì)陌生了吧施敢,看到了我們最熟悉的handleMessage()了周荐。這里就到了Handler對(duì)消息的處理階段了, 現(xiàn)在我們就可以在Handler所在的線程做自己想做的處理了僵娃。

尾語(yǔ)

到這里消息機(jī)制的流程我們已經(jīng)梳理完了概作,各部分的原理相信你也有了一定的了解,相信你現(xiàn)在回過(guò)頭去看前面的流程圖已經(jīng)有了不一樣的感覺(jué)了默怨。本人能力有限讯榕,只想分享一下自己的見(jiàn)解,希望我們一起進(jìn)步,有什么疏漏一定要聯(lián)系我哦S奁ā<弥瘛!很樂(lè)意與你交流探討v薄K妥恰!

注T匝唷:贝!

總結(jié)不易碍岔,請(qǐng)尊重勞動(dòng)成果浴讯,轉(zhuǎn)載請(qǐng)標(biāo)明出處,謝謝0病S芘Α!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末捏肢,一起剝皮案震驚了整個(gè)濱河市奈籽,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌鸵赫,老刑警劉巖衣屏,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異辩棒,居然都是意外死亡狼忱,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)一睁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)钻弄,“玉大人,你說(shuō)我怎么就攤上這事者吁【桨常” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵复凳,是天一觀的道長(zhǎng)瘤泪。 經(jīng)常有香客問(wèn)我,道長(zhǎng)育八,這世上最難降的妖魔是什么均芽? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮单鹿,結(jié)果婚禮上掀宋,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好劲妙,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布湃鹊。 她就那樣靜靜地躺著,像睡著了一般镣奋。 火紅的嫁衣襯著肌膚如雪币呵。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,604評(píng)論 1 305
  • 那天侨颈,我揣著相機(jī)與錄音余赢,去河邊找鬼。 笑死哈垢,一個(gè)胖子當(dāng)著我的面吹牛妻柒,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播耘分,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼举塔,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了求泰?” 一聲冷哼從身側(cè)響起央渣,我...
    開(kāi)封第一講書(shū)人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎渴频,沒(méi)想到半個(gè)月后芽丹,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡卜朗,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年志衍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片聊替。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖培廓,靈堂內(nèi)的尸體忽然破棺而出惹悄,到底是詐尸還是另有隱情,我是刑警寧澤肩钠,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布泣港,位于F島的核電站,受9級(jí)特大地震影響价匠,放射性物質(zhì)發(fā)生泄漏当纱。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一踩窖、第九天 我趴在偏房一處隱蔽的房頂上張望坡氯。 院中可真熱鬧,春花似錦、人聲如沸箫柳。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)悯恍。三九已至库糠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間涮毫,已是汗流浹背瞬欧。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留罢防,地道東北人艘虎。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像篙梢,于是被迫代替她去往敵國(guó)和親顷帖。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容