Android消息機(jī)制解析--Handler、Message贾节、Looper

前言

相信大家在開發(fā)過(guò)程中都使用過(guò)Handler,其中的原理是否已經(jīng)清楚了呢汁汗?如果沒有的話,看文章來(lái)一起分析一下吧~

源碼解析

首先我們查看Handler的無(wú)參構(gòu)造方法:

    public Handler() {
        this(null, false);
    }

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

在這里調(diào)用了Looper的myLooper方法:

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

這里使用了ThreadLocal栗涂,它的功能簡(jiǎn)單來(lái)說(shuō)就是:使用它的get方法時(shí)知牌,它會(huì)返回當(dāng)前線程對(duì)應(yīng)的變量值,在這里斤程,也就是返回當(dāng)前線程對(duì)應(yīng)的Looper角寸,如果當(dāng)前線程沒有關(guān)聯(lián)上Looper的話,就會(huì)返回null,那么扁藕,怎么才能讓線程和Looper關(guān)聯(lián)上呢墨吓?答案是Looper的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));
    }

可以看到,這里我們就將一個(gè)Looper和當(dāng)前線程關(guān)聯(lián)了起來(lái)纹磺,這里得到了第一條重要的結(jié)論:
如果要在某一個(gè)線程中創(chuàng)建Handler來(lái)接收消息并處理帖烘,那么首先要調(diào)用Looper的prepare方法來(lái)為當(dāng)前線程創(chuàng)建一個(gè)Looper,然后調(diào)用Looper.loop()開啟消息循環(huán)(下文會(huì)提到loop方法的作用)橄杨。這可能違背大家的開發(fā)經(jīng)驗(yàn):不對(duì)啊秘症,在主線程中使用Handler的時(shí)候我們并不需要調(diào)用Looper的prepare方法。其實(shí)這是因?yàn)槭浇茫骶€程中已經(jīng)為我們調(diào)用過(guò)了prepare:

 public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        Process.setArgV0("<pre-initialized>");

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

這里的prepareMainLooper方法也就是為主線程創(chuàng)建一個(gè)Looper并關(guān)聯(lián)乡摹,然后調(diào)用Looper.loop開啟了消息循環(huán)。

繼續(xù)看構(gòu)造函數(shù)采转,Looper中的Queue成員變量傳給了Handler聪廉,在下面分析Message入隊(duì)的時(shí)候,會(huì)看到它故慈。

接下來(lái)我們查看發(fā)送Message的方法:

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

可以看到板熊,最后都會(huì)轉(zhuǎn)到sendMessageAtTime方法中,跟進(jìn)enqueMessage方法察绷。

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

這里將handler對(duì)象賦給了Message對(duì)象的target成員變量干签,然后將Message加入到了隊(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;
    }

這個(gè)MessageQueue是用鏈表實(shí)現(xiàn)的拆撼,簡(jiǎn)單的說(shuō)容劳,上面的代碼做的事就是:根據(jù)這個(gè)Message的時(shí)間,將它插入到合適的位置闸度,我們知道竭贩,在sendMessage之后,往往handleMessage方法就會(huì)被自動(dòng)調(diào)用莺禁,中間到底發(fā)生了什么留量?
答案就在Looper中,查找發(fā)現(xiàn)loop方法:

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

相信大家看到這就明白了睁宰,Looper的loop方法執(zhí)行了一個(gè)無(wú)限循環(huán)肪获,每次循環(huán)都從隊(duì)列中取出一個(gè)Message,然后調(diào)用message.target.dispatchMessage方法柒傻,之前分析過(guò)孝赫,這個(gè)target應(yīng)該是一個(gè)handler對(duì)象,接下來(lái)去看看handler的這個(gè)方法:

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

這里就看到老熟人handleMessage了红符,到這里流程就大概走完了青柄,畫個(gè)圖總結(jié)一下:

消息機(jī)制流程

有問題歡迎評(píng)論探討~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末伐债,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子致开,更是在濱河造成了極大的恐慌峰锁,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,265評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件双戳,死亡現(xiàn)場(chǎng)離奇詭異虹蒋,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)飒货,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門魄衅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人塘辅,你說(shuō)我怎么就攤上這事晃虫。” “怎么了扣墩?”我有些...
    開封第一講書人閱讀 156,852評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵哲银,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我呻惕,道長(zhǎng)荆责,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,408評(píng)論 1 283
  • 正文 為了忘掉前任蟆融,我火速辦了婚禮草巡,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘型酥。我一直安慰自己,他們只是感情好查乒,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,445評(píng)論 5 384
  • 文/花漫 我一把揭開白布弥喉。 她就那樣靜靜地躺著,像睡著了一般玛迄。 火紅的嫁衣襯著肌膚如雪由境。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,772評(píng)論 1 290
  • 那天蓖议,我揣著相機(jī)與錄音虏杰,去河邊找鬼。 笑死勒虾,一個(gè)胖子當(dāng)著我的面吹牛纺阔,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播修然,決...
    沈念sama閱讀 38,921評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼笛钝,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼质况!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起玻靡,我...
    開封第一講書人閱讀 37,688評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤结榄,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后囤捻,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體臼朗,經(jīng)...
    沈念sama閱讀 44,130評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,467評(píng)論 2 325
  • 正文 我和宋清朗相戀三年蝎土,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了依溯。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,617評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瘟则,死狀恐怖黎炉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情醋拧,我是刑警寧澤慷嗜,帶...
    沈念sama閱讀 34,276評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站丹壕,受9級(jí)特大地震影響庆械,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜菌赖,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,882評(píng)論 3 312
  • 文/蒙蒙 一缭乘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧琉用,春花似錦堕绩、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至晶丘,卻和暖如春黍氮,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背浅浮。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工沫浆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人滚秩。 一個(gè)月前我還...
    沈念sama閱讀 46,315評(píng)論 2 360
  • 正文 我出身青樓专执,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親叔遂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子他炊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,486評(píng)論 2 348

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