Android Handler 機制(一):Handler 運行機制完整梳理


做Android開發的都應該知道Handler的運行機制,這個問題屬於老生常談了。

這里再簡單贅述一下:

  1. Handler 負責發送消息;
  2. Looper 負責接收 Handler 發送的消息,並在合適的時間將消息回傳給Handler;
  3. MessageQueue是一個存儲消息的隊列容器。

本文我們會詳細完整的將Handler的運行機制梳理一遍。

一、ActivityThread類和APP的啟動過程

為什么要講ActivityThread和App的啟動過程,因為Handler、Looper都是在這個階段進行創建和初始化的。

ActivityThread就是我們常說的主線程或UI線程,ActivityThread的main方法是一個APP的真正入口,MainLooper在它的main方法中被創建。

    //ActivityThread的main方法
    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        //在attach方法中會完成Application對象的初始化,然后調用Application的onCreate()方法
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ...
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

主線程的Handler作為ActivityThread的成員變量,是在ActivityThread的main方法被執行,ActivityThread被創建時進行初始化的。MessageQueue在Looper創建的時候作為成員變量被初始化創建。

二、Handler創建Message並發送給Looper

當我們創建一個Message並交給Handler發送的時候,內部調用的代碼如下:

public final boolean sendMessageDelayed(Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

 最終調用到的是MessageQueue的enqueueMessage方法,enqueueMessage 是核心處理方法。下面是MessageQueue.enqueueMessage方法的代碼:

    boolean enqueueMessage(Message msg, long when) {
        ...synchronized (this) { ... 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; }

這段代碼處理的事情就是將進入消息隊列的Message插入到合適的位置,並通過needWake判斷是否需要調用底層喚醒整個消息隊列。

結合上述的代碼,我們可以得出整體的邏輯如下所示:

          +-------+     +------------+   +------------------+   +--------------+                        
          |Handler|     |MessageQueue|   |NativeMessageQueue|   |Looper(Native)|                        
          +--+----+     +-----+------+   +---------+--------+   +-------+------+ | | | | | | | | sendMessage()| | | | +----------> | | | | | | | | |enqueueMessage()| | | +--------------> | | | | | | | | | | | | | nativeWake() | | | | wake() | | | +------------------> | | | | | | | | | wake() | | | +------------------> | | | | | | | | | | | | |write(mWakeWritePipeFd, "W", 1)  | | | | | | | | + + + + 

三、Looper循環處理MessageQueue的Message

我們知道Loop循環處理Message調用的方法是 Looper.loop()。

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

下面是MessageQueue的next方法的代碼:

    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 (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } 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; 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; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. 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. 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; } }

這段代碼處理的事情就是不斷從MessageQueue中取出消息,如果沒有消息的時候會給nativePollOnce的nextPollTimeoutMillis設置為-1,這時消息隊列就處於阻塞狀態了。

結合上述代碼,可以得出邏輯如下圖所示:

          +------+    +------------+  +------------------+  +--------------+                    
          |Looper|    |MessageQueue|  |NativeMessageQueue|  |Looper(Native)|                    
          +--+---+    +------+-----+  +---------+--------+  +-------+------+ | | | | +-------------------------------------------------------------------------------+ |[msg loop] | next() | | | | | +------------> | | | | | | | | | | | | | | | | | | | nativePollOnce() | | | | | | pollOnce() | | | | | +----------------> | | | | | | | | | | | | | | | | | | | | | | | | | pollOnce() | | | | | +-----------------> | | | | | | | | | | | | | epoll_wait() | | | | +--------+ | | | | | | | | | | | | | | | | | | | | <------+ | | | | | | awoken() | | + + + + | +-------------------------------------------------------------------------------+ 

四、總結

1. 相關知識點

HandlerThread、ThreadLocal、Linux Epoll 機制。

HandlerThread:

HandlerThread相比Thread最大的優勢在於引入MessageQueue概念,可以進行多任務隊列管理。HandlerThread背后只有一個線程,所以任務是串行依次執行的。串行相對於並行來說更安全,各任務之間不會存在多線程安全問題。HandlerThread所產生的線程會一直存活,Looper會在該線程中持續的檢查MessageQueue,並開啟消息處理的循環。這一點和Thread(),AsyncTask都不同,thread實例的重用可以避免線程相關的對象的頻繁重建和銷毀。 getLooper().quit();來退出這個線程,其實原理很簡單,就是改變在消息循環里面標志位,退出整個while循環,使線程執行完畢。

注意:要想更新界面內容,還是需要使用主線程的Looper,不然的話還是會拋錯誤。

2. 推薦文章:

1. Android Handler機制 - MessageQueue如何處理消息:https://blog.csdn.net/lovelease/article/details/81988696

2. ActivityThread的理解和APP的啟動過程:https://blog.csdn.net/hzwailll/article/details/85339714

3. 提高規划

嘗試使用Java代碼實現一個簡單的Handler-Looper框架。

代碼地址:http://suo.im/6iHMgy

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM