Android消息機制 Handler

在Android中解決子線程更新UI的三種方法:

  • Activity中 調(diào)用 runOnUiThread(Runnable action) {}
    源碼解析:

    /**
         * Runs the specified action on the UI thread. If the current thread is the UI
         * thread, then the action is executed immediately. If the current thread is
         * not the UI thread, the action is posted to the event queue of the UI thread.
         *
         * @param action the action to run on the UI thread
         */
        public final void runOnUiThread(Runnable action) {
            if (Thread.currentThread() != mUiThread) {
                mHandler.post(action);
            } else {
                action.run();
            }
        }
    
  • View 調(diào)用 View.post(Runnable action) {}
    源碼解析:

        /**
         * <p>Causes the Runnable to be added to the message queue.
         * The runnable will be run on the user interface thread.</p>
         *
         * @param action The Runnable that will be executed.
         *
         * @return Returns true if the Runnable was successfully placed in to the
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.
         *
         * @see #postDelayed
         * @see #removeCallbacks
         */
        public boolean post(Runnable action) {
            final AttachInfo attachInfo = mAttachInfo;
            if (attachInfo != null) {
                return attachInfo.mHandler.post(action);
            }
    
            // Postpone the runnable until we know on which thread it needs to run.
            // Assume that the runnable will be successfully placed after attach.
            getRunQueue().post(action);
            return true;
        }
    
  • 傳統(tǒng)的用法: handler.post()
    源碼解析:

    /**
         * Causes the Runnable r to be added to the message queue.
         * The runnable will be run on the thread to which this handler is 
         * attached. 
         *  
         * @param r The Runnable that will be executed.
         * 
         * @return Returns true if the Runnable was successfully placed in to the 
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.
         */
        public final boolean post(Runnable r)
        {
           return  sendMessageDelayed(getPostMessage(r), 0);
        }
    

    這三種方法最后都殊途同歸的調(diào)用了 handler.post(Runnable r). 而 handler.post 內(nèi)部卻調(diào)用的是 sendMessageDelayed(Message m , 0);

    所以最終的結(jié)論引入了 Handler 消息傳播機制。

Handler.post(Runnbale r) 的調(diào)用

首先查看 post 源碼

public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}

調(diào)用到 sendMessageDelayed 方法

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

延時發(fā)送消息,其實就是定時發(fā)送消息 sendMessageAtTime

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

最后執(zhí)行到 MessageQueue 輪循消息

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

引發(fā)的一些問題:

  • Handler Looper Message MessageQueue 怎么發(fā)生聯(lián)系?
  • Looper是什么?
  • Looper 和 MessageQueue 的關(guān)系?
  • Handler 會發(fā)生內(nèi)存泄露?為什么?

在handler創(chuàng)建的時候,handler 和 Looper 產(chǎn)生聯(lián)系: handler 的構(gòu)造函數(shù)如下:

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

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

在handler創(chuàng)建的時候,和handler所在線程的 looper 產(chǎn)生了關(guān)聯(lián)。在主線程中,Activity在創(chuàng)建的時候就幫我們創(chuàng)建了 looper 和 handler ,所以在子線程中更新ui的前兩種方法可以行得通。第三種更新方式,實際原理和前兩種一樣,只不過是手動在主線程中創(chuàng)建了handler.

注意: 因此在子線程中創(chuàng)建 handler 時候會報錯,只有開啟了 looper 才可以創(chuàng)建 handler

Looper相關(guān)知識點

  1. Looper類用來為一個線程開啟一個消息循環(huán)
    默認情況下android中新誕生的線程是沒有開啟消息循環(huán)的。(主線程除外,主線程系統(tǒng)會自動為其創(chuàng)建Looper對象,開啟消息循環(huán)。)
    Looper對象通過MessageQueue來存放消息和事件。一個線程只能有一個Looper,對應(yīng)一個MessageQueue。

  2. 通常是通過Handler對象來與 looper 進行交互的。
    Handler可看做是Looper的一個接口,用來向指定的Looper發(fā)送消息及定義處理方法。
    默認情況下Handler會與其被定義時所在線程的Looper綁定,比如,Handler在主線程中定義,那么它是與主線程的Looper綁定。
    mainHandler = new Handler() 等價于new Handler(Looper.myLooper()).
    Looper.myLooper():獲取當前進程的looper對象,類似的 Looper.getMainLooper() 用于獲取主線程的Looper對象。

  3. 在非主線程中直接new Handler() 會報如下的錯誤:
    E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
    E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    原因是非主線程中默認沒有創(chuàng)建Looper對象,需要先調(diào)用Looper.prepare()啟用Looper。

  4. Looper.loop(); 讓Looper開始工作,從消息隊列里取消息,處理消息。

    注意:寫在Looper.loop()之后的代碼不會被執(zhí)行,這個函數(shù)內(nèi)部應(yīng)該是一個循環(huán),當調(diào)用mHandler.getLooper().quit()后,loop才會中止,其后的代碼才能得以運行。

  5. 通過以上知識,可實現(xiàn)主線程給子線程(非主線程)發(fā)送消息。

Looper的使用過程以及和 Messagequeue 關(guān)系的建立:

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


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

Looper的調(diào)用方法是 Looper.prepare() -- new handler()-- looper.loop();

輪詢器在循環(huán)執(zhí)行 Messagequeue 中的消息時候調(diào)用的:

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;

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

        final long traceTag = me.mTraceTag;
        if (traceTag != 0) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

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

當執(zhí)行到其中的一條message時候, 會回調(diào)攜帶 message 的handler 的方法 dispatchMessage

msg.target.dispatchMessage(msg);

而在 Handler的 dispatchMessage(msg) 中又執(zhí)行了 callback.handleMessage(msg),

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

在callback的handleMessage(msg)中又接著執(zhí)行了 handler 的hanleMessage(msg) 方法;

/**
 * Subclasses must implement this to receive messages.
 */
public void handleMessage(Message msg) {
}
    

因此在創(chuàng)建 handler 的時候,一定要復(fù)寫其中的 handleMessage 方法.

總結(jié)

  1. 首先Looper.prepare() 在本線程創(chuàng)建并保存一個實例,然后該Loop實例創(chuàng)建并維護一個 MessageQueue 對象,因為一個線程中 Looper.prepare()只能執(zhí)行一次,因此 MessageQueue 只會存在一個。

  2. Looper.loop() 會讓當前線程進入一個無限循環(huán),不斷從消息隊列中讀取消息,并處理,此時會回調(diào) msg.target.dispatchMessage(msg)

  3. handler 的構(gòu)造方法會得到當前線程中保存的 looper 實例。

  4. Handler 的 sendMessage() 方法會給msg的 target 賦值為 handler 本身,然后加入到消息隊列中。

  5. 在構(gòu)造 handler 時候,我們會重寫 handlemessage() 方法,也是 msg.target.dispatchMessage(msg)最終調(diào)用的方法。

三者的關(guān)系如下面這個丑圖:

網(wǎng)上這個美圖更漂亮一些:

補充

  1. 為什么主線程中的Looper.loop() 一直無限循環(huán)不會造成 ANR?

答: ANR 的原因就是有需要處理的事情未處理,或者在規(guī)定時間內(nèi)未處理!
因為Android是由事件驅(qū)動的,looper.loop()不斷地接收事件、處理事件,每一個點擊、觸摸等等都在主線程looper.loop()的控制之下,如果它停止了,應(yīng)用也就停止了。只能說對消息的處理阻塞了主線程的looper.loop() 才會導(dǎo)致 ANR, looper.loop()會阻塞自己的運行???

  1. ANR的時間是多少?按鍵或者觸摸是5s,廣播是10s。官網(wǎng)的定義:
    https://developer.android.com/training/articles/perf-anr.html
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容