Android基礎(chǔ) Handler機(jī)制

引言

Handler機(jī)制是Android消息機(jī)制置森,是非常重要的需要深刻認(rèn)識的基礎(chǔ)知識蛹尝,在日后的開發(fā)中需要被頻繁用到的知識鹅士。

Handler機(jī)制中涉及Handler 褥影,Looper丈冬,MessageQueue宪塔,Message
接下來就讓我們從整體到局部的逐個(gè)說明下他們的關(guān)系

整體架構(gòu)

Handler梢杭,MessageQueue偏窝,Message衬吆,Looper四者之間的關(guān)系如下

Looper 是整體的老大梁钾,負(fù)責(zé)循環(huán)整個(gè)消息Message,MessageQueue則是Message的容器逊抡,而Handler不過是Android為了開發(fā)者封裝出來的一個(gè)用于消息創(chuàng)建姆泻,發(fā)送消息,消息事件回調(diào)的一個(gè)類冒嫡。

開始

我們從Android使用消息機(jī)制來說整個(gè)Handler機(jī)制的運(yùn)行過程拇勃。

首先是Android在程序啟動(dòng)的時(shí)候一切的開始之處ActivityThread中的main()方法中開始,這也是Android的UI主線程開始之處
5864F0FE-E2D8-44A3-8055-C095AFD2F8AD.png

如果所示表明了在main()中開始了這一消息之旅孝凌,那么Looper.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(); //1
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue; //2

        // 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 (;;) { //3
            Message msg = queue.next(); // might block //4
            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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg); //5
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

Looper的looper()方法主要是注釋的6個(gè)點(diǎn)以下將逐一介紹

  • 注釋1 中的Looper me = myLooper() 這里是為了獲取到Looper這個(gè)對象,那我們?nèi)タ聪?myLooper()方法到實(shí)現(xiàn) 如下
    /**
     * 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();
    }  

這里說明了是從sThreadLocal.get();中獲取那么 這里的THreadLocal又是什么鬼?答:ThreadLocal是Java中用于對不同線程存儲變量的一個(gè)類蟀架,類似一個(gè)Map的存儲類(key為對應(yīng)對線程瓣赂,value為存儲的值),那么sThreadLocal是什么時(shí)候賦值的 在上圖中往上看可以看到在Looper.loop()方法之前有調(diào)用Looper.prepareMainLooper();這里就是對Looper進(jìn)行賦值,將當(dāng)前線程與Looper進(jìn)行綁定辜窑。內(nèi)部方法如下

/**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false); 
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
     /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }

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

這樣就完成了Looper的綁定钩述。這里也說明了為什么在一個(gè)新的線程里為什么不調(diào)用Looper.prepare();直接使用Looper.loop()會crash,答案在如下代碼中(新的線程里沒有Looper所以肯定會報(bào)錯(cuò))

final Looper me = myLooper(); //1
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
  • 注釋2 就是獲取當(dāng)前Looper的MessageQueue (稍后會講解這個(gè)類的作用)
  • 注釋3 就開始Looper的死循環(huán) (這里為什么不會導(dǎo)致程序的ANR? 這里為什么會導(dǎo)致程序的ANR穆碎,要對ANR有一個(gè)詳細(xì)的了解牙勘,稍后會有一篇文章講解什么是ANR,為什么會一些操作導(dǎo)致ANR所禀,而不是什么死循環(huán)都會導(dǎo)致ANR)
  • 注釋4 就是從MessageQueue中獲取對應(yīng)的下一個(gè)Message方面,這里注意到在源碼注釋上 有一句 // might block 意思是可能會阻塞 這里我們需要深入的去看下源碼 (這里的解釋就直接在代碼后面以注釋的形式進(jìn)行講解)
Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {  //這里發(fā)現(xiàn)MessageQueue也是一個(gè)死循環(huán)
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
//這是JNI的方法,在JNI層等待被調(diào)用喚醒 就是這里可能會導(dǎo)致阻塞色徘,因?yàn)樵贘NI層等待下一個(gè)消息
            nativePollOnce(ptr, nextPollTimeoutMillis); 

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages; //獲取一個(gè)Message恭金,
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    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; //返回Message交給Looper處理
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                //如果沒有消息了則返回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();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    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.
            //處理注冊的IdleHandler褂策,當(dāng)MessageQueue中沒有消息的時(shí)候横腿,Looper會調(diào)用IdleHandler進(jìn)行一些工作颓屑,例如垃圾回收等。
            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;
        }
    }
  • 注釋5 就是將當(dāng)前執(zhí)行的消息事件回調(diào)出去耿焊,這里target就是Handler揪惦。
  • 注釋6 則是將當(dāng)前消息進(jìn)行回收

以上就是Looper.loop();方法的說明,也是Looper核心方法

接下來就是講一個(gè)Handler罗侯,Message器腋,MessageQueue類

Handler

Handler 我個(gè)人覺得它是Android給開發(fā)者的一個(gè)輔助類,它封裝了消息的投遞钩杰,消息處理回調(diào)

構(gòu)造函數(shù)(一切的開始)

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

  2. public Handler(Callback callback) { this(callback, false); }

  3. public Handler(Looper looper) { this(looper, null, false); }

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

  5. public Handler(boolean async) { this(null, async); }

  6. 實(shí)現(xiàn)1
    public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }

  7. 實(shí)現(xiàn)2

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)用了6纫塌,7這兩個(gè)就是將 mLooper,mQueue,mCallback,mAsynchronous 這四個(gè)賦值沒啥說的
Handler其他的方法就是 obtainMessage(),sendMessage(),dispatchMessage()沒什么說的讲弄,大家看下源碼就可以了

Message

小弟一樣的角色措左,就是用來發(fā)送承載東西的類,也沒什么說的

MessageQueue消息隊(duì)列

消息隊(duì)列用于處理獲取消息和插入消息垂睬,整體是一個(gè)隊(duì)列的形式

題外話-Android為什么為我們提供HandlerThread媳荒?

是因?yàn)槲覀儗懖幻靼讍峥购罚坎?是Android考慮到我們寫的不夠周全

比如我們?nèi)绻麑懢痛笾氯缦?div id="3nyubzp" class="image-package">
DF68FA7E-D050-4843-9290-320422C342A2.png

那么這里就有一個(gè)問題因?yàn)槭遣煌€程驹饺,執(zhí)行的先后順序無法保證 是先跑HandlerThread2.run()方法嗎?很不確定缴渊,這個(gè)時(shí)候mLooper就不一定賦值了赏壹,所以這個(gè)時(shí)候就會出現(xiàn)問題。所以系統(tǒng)為我們周全的寫了一個(gè)HandlerThread衔沼。就是為了解決這個(gè)問題 HandlerThread是通過鎖機(jī)制來獲取的蝌借。具體可以看下源碼。

最后

這就是我理解的Handler機(jī)制指蚁,如果哪里有錯(cuò)菩佑,歡迎指出來

參考Android源碼,《深入理解Android》卷1·第五章凝化,《深入理解Android》卷2·第二章

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末稍坯,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子搓劫,更是在濱河造成了極大的恐慌瞧哟,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件枪向,死亡現(xiàn)場離奇詭異勤揩,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)秘蛔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進(jìn)店門陨亡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來傍衡,“玉大人,你說我怎么就攤上這事负蠕〈鲜妫” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵虐急,是天一觀的道長箱残。 經(jīng)常有香客問我,道長止吁,這世上最難降的妖魔是什么被辑? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮敬惦,結(jié)果婚禮上盼理,老公的妹妹穿的比我還像新娘。我一直安慰自己俄删,他們只是感情好宏怔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著畴椰,像睡著了一般臊诊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上斜脂,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天抓艳,我揣著相機(jī)與錄音,去河邊找鬼帚戳。 笑死玷或,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的片任。 我是一名探鬼主播偏友,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼对供!你這毒婦竟也來了位他?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤犁钟,失蹤者是張志新(化名)和其女友劉穎棱诱,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涝动,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡迈勋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了醋粟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片靡菇。...
    茶點(diǎn)故事閱讀 39,779評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡重归,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出厦凤,到底是詐尸還是另有隱情鼻吮,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布较鼓,位于F島的核電站椎木,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏博烂。R本人自食惡果不足惜香椎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望禽篱。 院中可真熱鬧畜伐,春花似錦、人聲如沸躺率。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽悼吱。三九已至慎框,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間舆绎,已是汗流浹背鲤脏。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留吕朵,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓窥突,卻偏偏與公主長得像努溃,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子阻问,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評論 2 354

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