深入分析Android消息機(jī)制工作過程--Handler,Looper,MessageQueue

0.前言

image.png

Handler,Looper,MessageQueue三者配合共同完成Android的消息機(jī)制,每個(gè)線程都有自己的消息隊(duì)列桶良。消息機(jī)制是進(jìn)程起來就會(huì)從android.app.ActivityThread#main方法為main主線程創(chuàng)建一個(gè)MessageQueue消息隊(duì)列并通過Looper#loop方法進(jìn)入不斷從消息隊(duì)列獲取消息的過程。所以子線程需要自己添加一個(gè)線程隊(duì)列沮翔。

1.Handler,MessageQueue,Looper三角關(guān)系

Handler:負(fù)責(zé)生產(chǎn)消息陨帆,接收消息。將消息post到消息隊(duì)列MessageQueue中去采蚀。
Looper:負(fù)責(zé)循環(huán)從MessageQueue消息隊(duì)列中獲取消息疲牵,然后通過Handler分發(fā)消息出去各自處理。
MessageQueue:當(dāng)前線程的消息隊(duì)列榆鼠,用于接受Handler post過來的消息纲爸,存儲(chǔ)消息。

2.Handler工作過程分析

以下代碼我們平時(shí)開發(fā)過程中應(yīng)該非常熟悉妆够,我們就從這里分析识啦。

new Handler().post(new Runnable() {
            @Override
            public void run() {
                
            }
        });

首先我們從Handler post/postDelayed方法分析,具體這兩個(gè)方法僅僅從消息池中獲取一個(gè)消息實(shí)體神妹,然后將Runnable類型r賦值給callback颓哮,用于后面回調(diào)。方法如下:

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

我們可以看到post/postDelayed方法最終都是調(diào)用sendMessageDelayed方法鸵荠。

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

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

通過以上代碼queue.enqueueMessage(msg, uptimeMillis)可以看出题翻,其實(shí)就是將一個(gè)消息加入到消息隊(duì)列MessageQueue中。接下來我們繼續(xù)跟進(jìn)MessageQueue#enqueueMessage方法腰鬼。

3.MessageQueue工作過程分析

首頁我們看看MessageQueue這個(gè)消息隊(duì)列是什么時(shí)候創(chuàng)建的嵌赠。在這里我們大家平時(shí)開發(fā)過程中很少說到android程序的入口,學(xué)過C語言的同學(xué)應(yīng)該知道程序的入口就是main方法熄赡,那android是不是也用main方法呢姜挺?同樣也有,位于ActivityThread中main方法(android.app.ActivityThread#main)

public static void main(String[] args) {
     彼硫。
     炊豪。
     凌箕。
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        AsyncTask.init();

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

以上我們看到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();
        }
    }

再跟進(jìn)prepare方法如下:

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

我們看到sThreadLocal.set(new Looper(quitAllowed)),Looper構(gòu)造方法如下:

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

沒錯(cuò)就是這里词渤。然后我們跟進(jìn)到Looper構(gòu)造方法中牵舱,我們看到,原理MessageQueue是在Looper中初始化的缺虐。在這里我們看到sThreadLocal對(duì)象引用芜壁,這個(gè)其實(shí)就是一個(gè)本地變量副本,跟進(jìn)ThreadLocal.set(new Looper(quitAllowed))方法你可以看到其實(shí)跟線程有關(guān)聯(lián)了高氮。這里就不贅述了慧妄。具體看我上篇:ThreadLocal分析。到這里其實(shí)我們應(yīng)該可以知道每個(gè)線程都有自己的消息隊(duì)列剪芍。

接著我們看看消息加入隊(duì)列塞淹,源碼如下:

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 {
                // 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;
    }

4.Looper工作過程分析

首先我們從上面android.app.ActivityThread#main方法中我們可以看到,通過Looper.prepareMainLooper方法在Looper類中創(chuàng)建一個(gè)當(dāng)前本地線程關(guān)聯(lián)Looper對(duì)象并創(chuàng)建一個(gè)消息隊(duì)列罪裹。然后通過Looper.loop方法不斷的從消息隊(duì)列中獲取消息并通過Handler分發(fā)出對(duì)應(yīng)的消息饱普。下面我們重點(diǎn)看看Looper#loop方法:

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;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            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);

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

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            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();
        }
    }

1.通過myLooper獲取當(dāng)前線程的Looper對(duì)象。
2.獲取的myLooper不為空状共,這個(gè)時(shí)候取出Looper構(gòu)造函數(shù)中創(chuàng)建的MessageQueue消息隊(duì)列费彼。
3.然后進(jìn)入一個(gè)死循環(huán)中,通過queue.next取出下一個(gè)Message消息口芍,消息為空則直接返回箍铲,反之繼續(xù)執(zhí)行。
4.通過dispatchMessage方法分發(fā)消息出去鬓椭。這里我們看到是通過msg.target對(duì)象分發(fā)的颠猴,那msg.target是啥東西?我們看回android.os.Handler#enqueueMessage方法:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

將msg.target 賦值為 this小染,這里我們知道m(xù)sg.target其實(shí)就是一個(gè)Handler對(duì)象翘瓮。
5.接著我們繼續(xù)分析消息分發(fā)的過程,通過msg.target.dispatchMessage會(huì)調(diào)用android.os.Handler#dispatchMessage方法:

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

當(dāng)msg.callback不為空就調(diào)用handleCallback方法裤翩,msg.callback又是啥呢资盅?我們回憶下android.os.Handler#getPostMessage(java.lang.Runnable)方法:

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

msg.callback其實(shí)是Handler#post方法的一個(gè)Runnable對(duì)象。
反之當(dāng)msg.callback為空踊赠,同時(shí)mCallback不會(huì)空呵扛,就通過Callback接口回調(diào)到調(diào)用的地方,同時(shí)直接return筐带。

public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

通過上面可以看出mCallback是實(shí)例化Handler的時(shí)候傳進(jìn)來的今穿,則消息就會(huì)回調(diào)到對(duì)應(yīng)的handleMessage方法中。
到此整個(gè)消息機(jī)制的過程就分析完了伦籍。

That's All

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蓝晒,一起剝皮案震驚了整個(gè)濱河市腮出,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌芝薇,老刑警劉巖胚嘲,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異洛二,居然都是意外死亡馋劈,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門灭红,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人口注,你說我怎么就攤上這事变擒。” “怎么了寝志?”我有些...
    開封第一講書人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵娇斑,是天一觀的道長。 經(jīng)常有香客問我材部,道長毫缆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任乐导,我火速辦了婚禮苦丁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘物臂。我一直安慰自己旺拉,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開白布棵磷。 她就那樣靜靜地躺著蛾狗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪仪媒。 梳的紋絲不亂的頭發(fā)上沉桌,一...
    開封第一講書人閱讀 51,482評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音算吩,去河邊找鬼留凭。 笑死,一個(gè)胖子當(dāng)著我的面吹牛偎巢,可吹牛的內(nèi)容都是我干的冰抢。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼艘狭,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼挎扰!你這毒婦竟也來了翠订?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤遵倦,失蹤者是張志新(化名)和其女友劉穎尽超,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體梧躺,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡似谁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了掠哥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片巩踏。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖续搀,靈堂內(nèi)的尸體忽然破棺而出塞琼,到底是詐尸還是另有隱情,我是刑警寧澤禁舷,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布彪杉,位于F島的核電站,受9級(jí)特大地震影響牵咙,放射性物質(zhì)發(fā)生泄漏派近。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一洁桌、第九天 我趴在偏房一處隱蔽的房頂上張望渴丸。 院中可真熱鬧,春花似錦另凌、人聲如沸曙强。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽碟嘴。三九已至,卻和暖如春囊卜,著一層夾襖步出監(jiān)牢的瞬間娜扇,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來泰國打工栅组, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留雀瓢,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓玉掸,卻偏偏與公主長得像刃麸,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子司浪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

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