Handler知識收集整理-1

我是代碼搬運(yùn)工,不能僅僅只是搬運(yùn)笙隙,還要整理一下。

1. Handler組成部分:

  1. Message:消息
  2. Handler:消息的發(fā)起者
  3. Looper:消息的遍歷者
  4. MessageQueue:消息隊列
Handler流程圖

2. Handler的使用流程:

使用Handler之前的準(zhǔn)備工作有三步:

  1. 調(diào)用Looper.prepare()(主線程不需要調(diào)這個,因?yàn)锳PP創(chuàng)建時,main方法里面已經(jīng)幫我們創(chuàng)建了)

  2. 創(chuàng)建Handler對象赂毯,重寫handleMessage方法(你可以不重寫),用于處理message回調(diào)的

  3. 調(diào)用Looper.loop()

其中:

Looper.prepare()的作用主要有以下三點(diǎn):

  1. 創(chuàng)建Looper對象

  2. 創(chuàng)建MessageQueue對象拣宰,并讓Looper對象持有

  3. 讓Looper對象持有當(dāng)前線程


    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        // 規(guī)定了一個線程只有一個Looper党涕,也就是一個線程只能調(diào)用一次Looper.prepare()
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        // 如果當(dāng)前線程沒有Looper,那么就創(chuàng)建一個巡社,存到sThreadLocal中
        sThreadLocal.set(new Looper(quitAllowed));
    }
            
    

從上面的代碼可以看出膛堤,一個線程最多只有一個Looper對象。當(dāng)沒有Looper對象時晌该,去創(chuàng)建一個Looper肥荔,并存放到sThreadLocal中


    private Looper(boolean quitAllowed) {
        // 創(chuàng)建了MessageQueue,并供Looper持有
        mQueue = new MessageQueue(quitAllowed);
        // 讓Looper持有當(dāng)前線程對象
        mThread = Thread.currentThread();
    }
    

這里主要就是創(chuàng)建了消息隊列MessageQueue朝群,并讓它供Looper持有燕耿,因?yàn)橐粋€線程最多只有一個Looper對象,所以一個線程最多也只有一個消息隊列姜胖。然后再把當(dāng)前線程賦值給mThread誉帅。

Handler使用流程:

  1. Handler.post(或sendMessage): handler發(fā)送消息msg

  2. MessageQueue.enqueueMessage(msg, uptimeMillis):msg加入message隊列

  3. loop() 方法中從MessageQue中取出msg,然后回調(diào)handler的dispatchMessage右莱,然后執(zhí)行callback(如果有的話) 或 handleMessage蚜锨。(注意,loop方法是一直在循環(huán)的慢蜓,從前面的handler準(zhǔn)備工作開始就已經(jīng)一直在運(yùn)行了)

如圖所示:

ThreadLocal

3. Handler具體源碼:

3.1. Message獲取

Message的獲取方式有兩種:

1. Message msg = new Message();

2. Message msg = Message.obtain();

從全局池返回一個新的消息實(shí)例亚再。允許我們在許多情況下避免分配新對象。

    /**
     * Return a new Message instance from the global pool.      Allows us to
     * avoid allocating new objects in many cases.
     */
    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();
    }

復(fù)用之前用過的 Message 對象晨抡,這里實(shí)際上是用到了一種享元設(shè)計模式针余,這種設(shè)計模式最大的特點(diǎn)就是復(fù)用對象饲鄙,避免重復(fù)創(chuàng)建導(dǎo)致的內(nèi)存浪費(fèi)

    /**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
    
每次message使用完了之后會調(diào)用recycleUnchecked回收message凄诞,方便下次使用

Message核心的信息有這些:

    public int what;

    public int arg1;

    public int arg2;

    public Object obj;

    /*package*/ int flags;

    /*package*/ long when;

    /*package*/ Bundle data;

    /*package*/ Handler target;

    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    /*package*/ Message next;

3.2 Handler的發(fā)送消息

handler提供的發(fā)送消息的方法有很多圆雁,大致分為兩類:

  1. Handler.post(xxx);
  2. Handler.sendMessage(xxx);

雖然方法很多,但最終都會回調(diào)到這個方法:

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

這個方法就是將消息添加到隊列里帆谍。

3.3 MessageQueue的添加消息

enqueueMessage(添加消息)

源碼分析如下:


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

            // 標(biāo)記這個 Message 已經(jīng)被使用
            msg.markInUse();
            msg.when = when;
            // 這是這個消息隊列里的目前第一條待處理的消息(當(dāng)前消息隊列的頭部伪朽,有可能為空)
            Message p = mMessages;
            boolean needWake;
            // 如果目前隊列里沒有消息 或 這條消息msg需要立即執(zhí)行 或 這條消息msg的延遲時間比隊列里的第一條待處理的消息還要早的話,走這個邏輯
            if (p == null || when == 0 || when < p.when) {
                 // 把消息插入到消息隊列的頭部
                // 最新的消息汛蝙,如果已經(jīng)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循環(huán)的作用就是找出msg應(yīng)該放置的正確位置
                // 經(jīng)過下面這個for循環(huán),最終會找出msg的前一個消息是prev窖剑,后一個消息是p
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                // 上面的for循環(huán)得出的結(jié)果就是:msg應(yīng)該在prev后面坚洽,在p前面
                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;
    }

上面就是handler發(fā)送消息過來西土,然后添加到消息隊列里讶舰。

下面就開始講添加消息到隊列之后的事情:取消息,然后執(zhí)行需了。

3.4 Loop的取消息

前面已經(jīng)說到跳昼,在使用Handler之前有三步準(zhǔn)備工作:

  1. 調(diào)用Looper.prepare()(主線程不需要調(diào)這個,因?yàn)锳PP創(chuàng)建時肋乍,main方法里面已經(jīng)幫我們創(chuàng)建了)

  2. 創(chuàng)建Handler對象鹅颊,重寫handleMessage方法(你可以不重寫),用于處理message回調(diào)的

  3. 調(diào)用Looper.loop()

其中第三步的Looper.loop()的作用就是不斷的從MessageQueue隊列里取消息墓造,也就是說堪伍,在使用handler發(fā)消息之前,就已經(jīng)開始了loop的循環(huán)了觅闽。

loop()源碼比較長帝雇,這里摘取核心部分:


    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     *
     * 大概的翻譯就是:在這個線程中運(yùn)行消息隊列。確保調(diào)用{@link #quit()}來結(jié)束循環(huán)谱煤。
     *
     */
    public static void loop() {
    
        ····
        ····

        for (;;) {
            // 不斷的從MessageQueue的next方法里取出隊列的頭部消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ·····
            ·····
            ·····
           
            try {
                // msg.target是Message在創(chuàng)建時傳入的Handler摊求,也就是發(fā)送這條消息的發(fā)送者h(yuǎn)andler
                // 所以最終會回調(diào)到handler的dispatchMessage方法
                
                msg.target.dispatchMessage(msg);
                
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            
           
           ····
           ····
            
            // 回收msg,重復(fù)利用
            msg.recycleUnchecked();
        }
    }

loop()的作用就是不斷的從MessageQueue里取消息刘离,然后回調(diào)到dispatchMessage里室叉,再看看dispatchMessage里干啥了


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

所以最終會執(zhí)行callback或handleMessage。

簡書對文章長度有限制硫惕,剩下的放到下一篇文章:

(Handler知識收集整理-2)

http://www.reibang.com/p/9d3aa5a06661

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末茧痕,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子恼除,更是在濱河造成了極大的恐慌踪旷,老刑警劉巖曼氛,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異令野,居然都是意外死亡舀患,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門气破,熙熙樓的掌柜王于貴愁眉苦臉地迎上來聊浅,“玉大人,你說我怎么就攤上這事现使〉统祝” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵碳锈,是天一觀的道長顽冶。 經(jīng)常有香客問我,道長售碳,這世上最難降的妖魔是什么强重? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮团滥,結(jié)果婚禮上竿屹,老公的妹妹穿的比我還像新娘。我一直安慰自己灸姊,他們只是感情好拱燃,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著力惯,像睡著了一般碗誉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上父晶,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天哮缺,我揣著相機(jī)與錄音,去河邊找鬼甲喝。 笑死尝苇,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的埠胖。 我是一名探鬼主播糠溜,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼直撤!你這毒婦竟也來了非竿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤谋竖,失蹤者是張志新(化名)和其女友劉穎红柱,沒想到半個月后承匣,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡锤悄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年韧骗,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铁蹈。...
    茶點(diǎn)故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡宽闲,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出握牧,到底是詐尸還是另有隱情,我是刑警寧澤娩梨,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布沿腰,位于F島的核電站,受9級特大地震影響狈定,放射性物質(zhì)發(fā)生泄漏颂龙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一纽什、第九天 我趴在偏房一處隱蔽的房頂上張望措嵌。 院中可真熱鬧,春花似錦芦缰、人聲如沸企巢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽浪规。三九已至,卻和暖如春探孝,著一層夾襖步出監(jiān)牢的瞬間笋婿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工顿颅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留缸濒,地道東北人。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓粱腻,卻偏偏與公主長得像庇配,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子栖疑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評論 2 355

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