Handler常見疑問

Handler 是用來做什么的述吸?

總的來說剩彬,Handler可以跨線程發(fā)送Message

對應(yīng)用層來說阿纤,Android不允許主線程以外的線程更新UI凳厢,所以需要借助Handler來更新UI

對Framework來說,AMS通過Binder跨進(jìn)程悟耘,發(fā)送消息到ApplicationThread落蝙,ApplicationThreadH(繼承自Handler)發(fā)送消息,H收到消息后再ActivityThread中處理

Handler Looper MessageQueue Message 四者關(guān)系暂幼?

一次完整的Handler使用流程是怎么樣的筏勒?

使用流程
使用流程

一、Looper.prepare( ):

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //設(shè)置Looper到ThreadLocal
        sThreadLocal.set(new Looper(quitAllowed));
    }

二旺嬉、在消費線程實例化Handler管行,Handler在ThreadLocal中放置屬于此線程的Looper。設(shè)置將來獲得Message的方法(復(fù)寫dispatchMessage()方法邪媳,或者通過接口回調(diào))

Handler 所有的構(gòu)造方法:


Handler 所有的構(gòu)造方法
Handler 所有的構(gòu)造方法

Handler獲得Looper有兩種途徑:

  1. 構(gòu)造方法
  2. Looper.myLooper()的靜態(tài)方法
    public Handler(Callback callback, boolean async) {
        //Looper從ThreadLocal獲得該線程的mLooper
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        //獲得該線程的MessageQueue
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

三捐顷、在另一個線程,用Handler的引用雨效,發(fā)送Message

    //最終會調(diào)用該方法
    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) {
        //在Message中保存該Handler的引用
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //插入一條消息到單鏈表MessageQueue
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        //重復(fù)生產(chǎn)了多條相同的Message而沒有被消費掉
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            //已經(jīng)沒有Looper啦迅涮,插不進(jìn)去了
            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;
            }
            //標(biāo)記正在使用
            msg.markInUse();
            msg.when = when;
            //哨兵
            Message p = mMessages;
            boolean needWake;
            //此次傳入的msg為頭
            if (p == null || when == 0 || when < p.when) {
                //設(shè)置哨兵
                msg.next = p;
                //mMessage更新為該msg
                mMessages = msg;
                needWake = mBlocked;
            } else {
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                //prev為msg的前一個
                Message prev;
                for (;;) {
                    //既然p不為空,p即使msg的前一個
                    prev = p;
                    //更新p為p的下一個
                    p = p.next;
                    //p的下一個為空徽龟,意味著到達(dá)尾部叮姑,跳出
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                //msg的下一個為p,p為空
                msg.next = p;
                //插入到末尾
                prev.next = msg;
            }
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

四据悔、Looper.loop()

    public static void loop() {
        //獲得屬于該線程的Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //獲得MessageQueue
        final MessageQueue queue = me.mQueue;

        for (;;) {
            //循環(huán)去獲取下一條消息
            Message msg = queue.next(); 
            //queue.next()返回null <==> 該線程的looper退出了
            if (msg == null) {
                return;
            }
            try {
                //msg.target返回Handler传透,Handler.dispatchMessage(msg)完成消息的傳遞
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
        }
    }
Message next() {
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }
        int pendingIdleHandlerCount = -1;
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //沒有消息的話線程進(jìn)入休眠
            nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
                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) {
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        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 {
                    nextPollTimeoutMillis = -1;
                }
                if (mQuitting) {
                    dispose();
                    return null;
                }
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    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;
        }
    }

Looper到底保存在哪里的?

一個線程一般私有三種類型的數(shù)據(jù):

  1. Thread Local Storage
  2. 寄存器

在一個線程調(diào)用Looper.prepare()后屠尊,會實例化一個Looper對象,保存在Thread Local Storage中耕拷。 Handler可以從TLS中獲得Looper的引用讼昆,這樣就可以把Thread和Looper形成一一對應(yīng)的關(guān)系

Handler如何循環(huán)?

調(diào)用Looper.loop( )后骚烧,會進(jìn)入一個永真循環(huán)浸赫,去調(diào)用queue.next( )

而queue.next( )又是一個永真循環(huán),不斷查詢是否有新的消息

循環(huán)在什么時候退出赃绊?

對于Looper.loop()中的循環(huán)既峡,當(dāng)且僅當(dāng)queue.next()返回null時退出
對于queue.next()中的循環(huán),當(dāng)且僅當(dāng)mQuitting為真時退出

queue.next()什么時候會返回null呢碧查?

查看源碼我們發(fā)現(xiàn)有兩處return null

if (ptr == 0) {
    return null;
}
if (mQuitting) {
    dispose();
    return null;
}

對于第一處:
當(dāng)一個線程的Looper已經(jīng)退出运敢,并且所有的消息都處理了校仑,如果再重啟這個Looper,就會使得ptr==0為真
意思就是一個線程處理了所有事件传惠,手動退出Looper迄沫。以后就算再重新調(diào)用Looper.loop(),也是不能正常收到事件的

對于第二處:
當(dāng)mQuitting為真會進(jìn)入該段代碼

那什么情況下mQuitting會為真呢

在Looper.quit( ):

    public void quit() {
        mQueue.quit(false);
    }

MessageQueue.quit():

    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

可以發(fā)現(xiàn)卦方,當(dāng)且僅當(dāng)我們調(diào)用了MessageQueue.quit()羊瘩,mQuitting為真,MessageQueue.next()返回null盼砍,跳出循環(huán)尘吗,進(jìn)而調(diào)到next()方法的Looper.loop()方法也跳出循環(huán)

也就是說,只有我們調(diào)用了Looper.quit()后浇坐,循環(huán)才會停止

同時我們注意到了throw new IllegalStateException("Main thread not allowed to quit.");這個異常睬捶,也就是說我們不可能主動退出主線程的Looper,不能手動停止主線程的消息循環(huán)

主線程的Handler在哪實例化的吗跋?Looper又在哪里調(diào)用prepare( )和loop( )的侧戴?

在ActivityThread中有以下代碼

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();
        CloseGuard.setEnabled(false);
        Environment.initForCurrentUser();
        EventLogger.setReporter(new EventLoggingReporter());
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("<pre-initialized>");
        //準(zhǔn)備主線程的Looper
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        //創(chuàng)建ApplicationThread,即開啟Binder跌宛,接收AMS消息
        thread.attach(false);
        //實例化Handler酗宋,此Handler接收ApplicationThread的消息
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        //Looper.loop( )
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

可以看見我們調(diào)用Looper.prepareMainLooper()來準(zhǔn)備我們主線程的Looper
該方法會檢查主線程的Looper是否已經(jīng)創(chuàng)建過了,如果創(chuàng)建過了疆拘,就拋出異常
并且設(shè)置主線程的Looper是不允許退出的蜕猫,而且,只有主線程的Looper能夠有此殊榮

主線程的Handler類名叫H哎迄,是ActivityThread類的內(nèi)部類

handleMessage(Message msg)方法負(fù)責(zé)分發(fā)事件回右,這個方法在ApplicationThreadsendMessage()方法調(diào)用,ApplicationThread繼承自Binder漱挚,接收來自AMS的IPC消息

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末翔烁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子旨涝,更是在濱河造成了極大的恐慌蹬屹,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件白华,死亡現(xiàn)場離奇詭異慨默,居然都是意外死亡,警方通過查閱死者的電腦和手機弧腥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進(jìn)店門厦取,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人管搪,你說我怎么就攤上這事虾攻≌÷颍” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵台谢,是天一觀的道長寻狂。 經(jīng)常有香客問我,道長朋沮,這世上最難降的妖魔是什么蛇券? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮樊拓,結(jié)果婚禮上纠亚,老公的妹妹穿的比我還像新娘。我一直安慰自己筋夏,他們只是感情好蒂胞,可當(dāng)我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著条篷,像睡著了一般骗随。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赴叹,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天鸿染,我揣著相機與錄音,去河邊找鬼乞巧。 笑死涨椒,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的绽媒。 我是一名探鬼主播蚕冬,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼是辕!你這毒婦竟也來了囤热?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤获三,失蹤者是張志新(化名)和其女友劉穎旁蔼,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體石窑,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡牌芋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年蚓炬,在試婚紗的時候發(fā)現(xiàn)自己被綠了松逊。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡肯夏,死狀恐怖经宏,靈堂內(nèi)的尸體忽然破棺而出犀暑,到底是詐尸還是另有隱情,我是刑警寧澤烁兰,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布耐亏,位于F島的核電站,受9級特大地震影響沪斟,放射性物質(zhì)發(fā)生泄漏广辰。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一主之、第九天 我趴在偏房一處隱蔽的房頂上張望择吊。 院中可真熱鬧,春花似錦槽奕、人聲如沸几睛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽所森。三九已至,卻和暖如春夯接,著一層夾襖步出監(jiān)牢的瞬間焕济,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工钻蹬, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留吼蚁,地道東北人。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓问欠,卻偏偏與公主長得像肝匆,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子顺献,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,933評論 2 355

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