Handler在Android中的那些事

前言

在Android開發(fā)過程中,使用Handler已經(jīng)是一件很平常的事了民逼。比如經(jīng)常遇到在子線程中如何更新UI胖替,AsyncTask的實(shí)現(xiàn),IntentService是如何實(shí)現(xiàn)在子線程工作的恋昼,當(dāng)碰到這些問題的時(shí)候,一下子就想到是Handler通過發(fā)送消息來實(shí)現(xiàn)的赶促。那么Handler是如何實(shí)現(xiàn)消息發(fā)送機(jī)制的呢液肌?

Handler工作流程

說到Handler,就要提起MessageQueue鸥滨,Looper嗦哆,Message。通常做法是在線程A中通過Handler發(fā)送一條消息Message到消息隊(duì)列MessageQueue婿滓,而Looper會(huì)在MessageQueue有消息到達(dá)時(shí)取出消息Message并且發(fā)送給Handler.dispatchMessage處理吝秕。它們之間的關(guān)系如下圖:


handler流程.png

new Handler()

public Handler(@Nullable Callback callback, boolean async) {
        // Looper.myLooper() =>  sThreadLocal.get()
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

通過創(chuàng)建Handler的源碼可以發(fā)現(xiàn),會(huì)先取Looper.myLooper()空幻,如果mLooper為空會(huì)拋出異常烁峭,看異常錯(cuò)誤可以得知是在當(dāng)前線程中沒有調(diào)用Looper.prepare()。那么為什么我們?cè)谥骶€程直接new Handler不會(huì)拋出異常呢秕铛?是因?yàn)閦ygote啟動(dòng)應(yīng)用進(jìn)程的時(shí)候约郁,在ActivityThread.main()中已經(jīng)給主線程創(chuàng)建了Looper,如下代碼所示:

public static void main(String[] args) {
        // ...省略其他代碼
        // 最終也是執(zhí)行Looper.prepare()
        Looper.prepareMainLooper();
        // ...省略其他代碼
        //獲取的是H類的實(shí)例但两,H類也是繼承Handler
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        //開啟死循環(huán)
        Looper.loop();
        //一旦 Looper.loop() 執(zhí)行結(jié)束鬓梅,那么就拋出異常了
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

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

首先會(huì)執(zhí)行sThreadLocal.get(),如果不為空則拋出異常谨湘,這里也解釋了為什么一個(gè)線程只能創(chuàng)建一個(gè)Looper的問題绽快;如果為空,則創(chuàng)建一個(gè)Looper設(shè)置給sThreadLocal紧阔,這樣就實(shí)現(xiàn)了Looper和ThreadLocal的雙向綁定坊罢。使用ThreadLocal就能達(dá)到線程間數(shù)據(jù)互不干擾的效果,這樣的設(shè)計(jì)也能避免線程間共享的數(shù)據(jù)不會(huì)錯(cuò)亂擅耽。接下來看下new Looper(quitAllowed)做了什么

new Looper(quitAllowed)

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

私有構(gòu)造函數(shù)也說明在創(chuàng)建Looper的時(shí)候是不允許通過new來創(chuàng)建的活孩,只能通過
Looper.prepare()來創(chuàng)建。在創(chuàng)建Looper的時(shí)候也創(chuàng)建了當(dāng)前線程的MessageQueue乖仇。接下來就是開始消息循環(huán)Looper.loop()

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;
        // ...省略代碼
        for (;;) {
            //從MessageQueue中取消息憾儒,沒有消息會(huì)阻塞,nativePollOnce
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            // ...省略代碼
            try {
                // msg.target == handler
                msg.target.dispatchMessage(msg);
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
           // ...省略代碼
           // 這里是回收msg的邏輯乃沙,提高性能和內(nèi)存
            msg.recycleUnchecked();
        }
    }

首先還是判斷當(dāng)前線程是否有Looper,如果沒有拋出異常起趾,否則獲取當(dāng)前MessageQueue,通過死循環(huán)來調(diào)用MessageQueue的next方法獲取消息警儒,如果沒有消息則會(huì)阻塞训裆,阻塞是在MessageQueue.next方法中實(shí)現(xiàn),后面會(huì)分析。當(dāng)沒有獲取到消息的會(huì)直接退出循環(huán)缭保,這也是退出Looper的原因汛闸,而觸發(fā)的原因是調(diào)用了Looper.quit()間接的調(diào)用MessageQueue.quit()實(shí)現(xiàn)的。如果獲取到了消息艺骂,則調(diào)用msg.target.dispatchMessage(msg)來處理消息诸老,在MessageQueue.enqueueMessage給Message.target賦值為了當(dāng)前的Handler,這樣就能執(zhí)行到Handler.dispatchMessage中去了钳恕。所以也可以得到消息處理是在創(chuàng)建Handler所使用的Looper的線程中别伏,從而達(dá)到線程切換的目的。

MessageQueue的生產(chǎn)者enqueueMessage()

當(dāng)我們?cè)贖andler中發(fā)送消息時(shí)忧额,最終都會(huì)調(diào)用MessageQueue.enqueueMessage方法厘肮,使得消息入隊(duì)。

boolean enqueueMessage(Message msg, long when) {
        //判斷msg必須得有Handler
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        //判斷當(dāng)前msg還沒有被處理過
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }
        //MessageQueue是生產(chǎn)者消費(fèi)者睦番,在next方法中同樣有synchronized (this) 类茂,這里是生產(chǎn)者
        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) {
                  //如果msg是第一條消息或者執(zhí)行時(shí)間小于當(dāng)前第一條消息則放在鏈表第一條托嚣,并且將needWake置為mBlocked巩检,mBlocked是在next中賦值的,下面分析
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //消息按照時(shí)間來插入到鏈表中
                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;
            }
            // 如果需要喚醒示启,則調(diào)用nativeWake來喚醒被nativePollOnce掛起的線程
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

MessageQueue是一種生產(chǎn)者消費(fèi)者模式兢哭,enqueueMessage方法內(nèi)部用synchronized (this)獲取當(dāng)前對(duì)象的鎖,將msg按照?qǐng)?zhí)行的時(shí)間順序添加到MessageQueue中夫嗓,如果當(dāng)前線程是被掛起的狀態(tài)迟螺,還要通過nativeWake來喚醒線程。

MessageQueue的消費(fèi)者next()

從前面我們可以知道舍咖,在Looper.loop()開啟死循環(huán)后矩父,就在等待MessageQueue.next()返回可以處理的消息。

Message next() {
       //如果消息隊(duì)列已經(jīng)退出了谎仲,則就返回null浙垫,那么在looper.loop()就會(huì)得null的message,從而退出
        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();
            }
            //掛起當(dāng)前線程郑诺,native中通過epoll_wait()來阻塞的
            nativePollOnce(ptr, nextPollTimeoutMillis);
            //這里的 synchronized (this)是消費(fèi)者
            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) {
                    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;
                }

                //mQuitting是quit()函數(shù)賦值的,如果mQuitting為true表示消息隊(duì)列要退出了杉武,返回msg=null辙诞;
                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();
                }
                //如果msg==null時(shí),nextPollTimeoutMillis = -1轻抱,之所以nextPollTimeoutMillis沒有執(zhí)行循環(huán)末尾的重新賦值為0飞涂,就是因?yàn)檫@里需要執(zhí)行空閑時(shí)的IdleHandler個(gè)數(shù)為0,continue后,執(zhí)行nativePollOnce進(jìn)入了阻塞
                if (pendingIdleHandlerCount <= 0) {
                    //阻塞掛起较店,并且賦值 mBlocked為true士八,那么下次有消息時(shí),在enqueueMessage方法中就要喚醒被掛起的線程
                    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;
        }
    }

首先判斷消息隊(duì)列是否退出梁呈,如果退出則直接返回null給Looper退出婚度,沒有退出則繼續(xù)執(zhí)行。nativePollOnce(ptr, nextPollTimeoutMillis)是通過nextPollTimeoutMillis來說明當(dāng)前是否需要掛起和掛起時(shí)間官卡。當(dāng)nextPollTimeoutMillis==-1時(shí)表示一直阻塞不會(huì)超時(shí)蝗茁;當(dāng)nextPollTimeoutMillis==0時(shí)表示不會(huì)阻塞立即返回;當(dāng)nextPollTimeoutMillis>0時(shí)表示當(dāng)前線程最長需要掛起多長時(shí)間寻咒。局部變量nextPollTimeoutMillis初始值為0哮翘,進(jìn)入同步代碼塊后,如果獲取到當(dāng)前msg為空毛秘,則nextPollTimeoutMillis=-1饭寺,我們可以發(fā)現(xiàn)在循環(huán)末尾會(huì)重新給nextPollTimeoutMillis賦值為0,那么nativePollOnce就不會(huì)阻塞掛起了叫挟。但其實(shí)還要注意到pendingIdleHandlerCount這個(gè)空閑時(shí)可處理的IdleHandler個(gè)數(shù)艰匙,如果沒有添加的IdleHandler那么就是0,所以這里執(zhí)行continue后霞揉,繼續(xù)for循環(huán)nativePollOnce(ptr,-1)阻塞掛起了旬薯。如果msg!=null的時(shí)候,就會(huì)比較當(dāng)前時(shí)間是否小于消息執(zhí)行的時(shí)間适秩,如果小于的話绊序,線程就會(huì)進(jìn)入最長需要掛起的時(shí)間;如果大于就返回當(dāng)前的msg秽荞。

執(zhí)行工作的Handler.dispatchMessage()

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

如果msg的callback不為空骤公,就執(zhí)行msg的callback.run(),如果調(diào)用Handler.post系列的方法扬跋。如果msg.callback為空阶捆,則判斷Callback是否為空,不為空就執(zhí)行mCallback的handleMessage方法钦听,最后才執(zhí)行Handler的handleMessage洒试,這也是平常用的最多的。

Message.recycleUnchecked()

在Looper.loop()執(zhí)行完msg.target.dispatchMessage(msg)后朴上,還會(huì)執(zhí)行msg.recycleUnchecked()垒棋。

void recycleUnchecked() {
        // ...省略初始化代碼
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

如果當(dāng)前sPoolSize還沒有到MAX_POOL_SIZE(50個(gè)),就把當(dāng)前的msg放入隊(duì)列的頭部痪宰。這種方式相比于new Message()叼架,可以提升內(nèi)存的使用率畔裕,如果一直new實(shí)例,則在內(nèi)存空間上就會(huì)出現(xiàn)很多碎片乖订,也可能造成頻繁gc扮饶。所以推薦使用Handler.obtainMessage()

public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

Looper.quit()和quitSafely()

如果在子線程中創(chuàng)建了Looper,就可以通過quit或者quitSafely來退出消息隊(duì)列乍构。這樣可以停止線程的Looper.loop()甜无,并且不會(huì)有內(nèi)存泄漏問題。quit和quitSafely的區(qū)別就是蜡吧,quit會(huì)移除所有的消息毫蚓,quitSafely只會(huì)移除還沒處理的消息。
至此昔善,就明白Android中Handler的工作原理元潘,再去看AsyncTask,IntentService,HandlerThread就比較容易理解了。

總結(jié):

1.使用handler之前必須先調(diào)用Looper.prepare來創(chuàng)建Looper君仆,否則會(huì)報(bào)異常翩概。所以在子線程需要執(zhí)行Looper.prepare(),通過Looper.myLooper()來獲取當(dāng)前線程的Looper返咱,一個(gè)線程只有一個(gè)Looper和MessageQueue钥庇。主線程不用執(zhí)行是因?yàn)樵贏ctivityThread.main中已經(jīng)執(zhí)行了Looper.prepareMainLooper()
2.處理Handler消息的線程是Looper所在的線程,所以在IntentService中雖然在主線程中創(chuàng)建的ServiceHandler,但是Looper是HandlerThread中的子線程Looper,所以在處理消息onHandleIntent()時(shí)是在子線程處理的咖摹,可以做耗時(shí)操作
3.MessageQueue消息隊(duì)列是生產(chǎn)者消費(fèi)者模式评姨,在添加消息是按照?qǐng)?zhí)行的時(shí)間when順序插入到鏈表中去的。
4.Looper.loop()死循環(huán)不會(huì)導(dǎo)致ANR萤晴,因?yàn)樵跊]有消息時(shí)會(huì)阻塞并且掛起當(dāng)前線程吐句,而不會(huì)超時(shí),只有超時(shí)沒有響應(yīng)才會(huì)導(dǎo)致ANR店读。當(dāng)MessageQueue沒有消息時(shí)嗦枢,會(huì)調(diào)用nativePollOnce導(dǎo)致線程阻塞,直到有消息到達(dá)時(shí)調(diào)用nativeWake來喚醒線程屯断。
5.如果需要退出Looper文虏,可以調(diào)用Looper.quit()或者quitSafely(),但是主線程是不能退出的殖演,因?yàn)橹骶€程在mQuitAllowed為false氧秘,調(diào)用quit會(huì)直接異常。
6.在使用Message時(shí)趴久,最好使用Handler.obtainMessage來取代new Message()
7.Handler引起內(nèi)存泄漏的原因敏储,在發(fā)送消息的時(shí)候msg會(huì)引用Hanlder作為target成員變量的值。在子線程中沒有釋放Looper對(duì)象朋鞍。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
禁止轉(zhuǎn)載已添,如需轉(zhuǎn)載請(qǐng)通過簡信或評(píng)論聯(lián)系作者。
  • 序言:七十年代末滥酥,一起剝皮案震驚了整個(gè)濱河市更舞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌坎吻,老刑警劉巖缆蝉,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異瘦真,居然都是意外死亡刊头,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門诸尽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來原杂,“玉大人,你說我怎么就攤上這事您机〈┮蓿” “怎么了?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵际看,是天一觀的道長咸产。 經(jīng)常有香客問我,道長仲闽,這世上最難降的妖魔是什么脑溢? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮赖欣,結(jié)果婚禮上屑彻,老公的妹妹穿的比我還像新娘。我一直安慰自己畏鼓,他們只是感情好酱酬,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著云矫,像睡著了一般膳沽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上让禀,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天挑社,我揣著相機(jī)與錄音,去河邊找鬼巡揍。 笑死痛阻,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的腮敌。 我是一名探鬼主播阱当,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼俏扩,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了弊添?” 一聲冷哼從身側(cè)響起录淡,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎油坝,沒想到半個(gè)月后嫉戚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡澈圈,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年彬檀,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瞬女。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡窍帝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出拆魏,到底是詐尸還是另有隱情盯桦,我是刑警寧澤,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布渤刃,位于F島的核電站拥峦,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏卖子。R本人自食惡果不足惜略号,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望洋闽。 院中可真熱鬧玄柠,春花似錦、人聲如沸诫舅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽刊懈。三九已至这弧,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間虚汛,已是汗流浹背匾浪。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留卷哩,地道東北人蛋辈。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像将谊,于是被迫代替她去往敵國和親冷溶。 傳聞我的和親對(duì)象是個(gè)殘疾皇子渐白,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

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