Android Handler機(jī)制8之消息的取出與消息的其他操作

Android Handler機(jī)制系列文章整體內(nèi)容如下:

本片文章的主要內(nèi)容如下:

  • 1、消息的取出
  • 2、消息(Message)的移除
  • 3、關(guān)閉消息隊(duì)列
  • 4、查看消息是否存在
  • 5、阻塞非安全執(zhí)行

一、消息的取出

(一)、消息的取出主要是通過(guò)Looper的loop方法

代碼如下Looper.java 122行

  /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
         //第1步
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //第2步
        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();

         //第3步
        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.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                // 第5步
                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);
            }
            // 第6步
            msg.recycleUnchecked();
        }
    }

這個(gè)方法已經(jīng)在Android Handler機(jī)制4之Looper與Handler簡(jiǎn)介中說(shuō)過(guò)了,我就重點(diǎn)說(shuō)下流程,大體上分為6步

  • 第1步 獲取Looper對(duì)象
  • 第2步 獲取MessageQueue消息隊(duì)列對(duì)象
  • 第3步 while()死循環(huán)遍歷
  • 第4步 通過(guò)queue.next()來(lái)從MessageQueue的消息隊(duì)列中獲取一個(gè)Message msg對(duì)象
  • 第5步 通過(guò)msg.target. dispatchMessage(msg)來(lái)處理消息
  • 第6步 通過(guò)msg.recycleUnchecked()方來(lái)回收Message到消息對(duì)象池中

由于第1步、第2步第3步比較簡(jiǎn)單就不講解了,而第6步y已經(jīng)講解過(guò),也不講解了,下面我們來(lái)重點(diǎn)說(shuō)下第4步第5步

(二)、Message next()方法

從消息隊(duì)列中提取Message交給Looper來(lái)處,這個(gè)步驟應(yīng)該是MessageQueue乃至整個(gè)線程消息機(jī)制的核心了,所以我們將這部分放到最后來(lái)將,因?yàn)槠鋬?nèi)部的代碼邏輯比較復(fù)雜,涉及到了障柵如何攔截同步消息、如何阻塞線程、如何在空閑的時(shí)候執(zhí)行IdleHandler以及如何關(guān)閉Looper等內(nèi)容,在源碼已經(jīng)做了詳細(xì)的注釋,不過(guò)由于邏輯比較復(fù)雜所以想要看明白,大家還要花費(fèi)一定時(shí)間的。

PS:在Looper.loop()中獲取消息的方式就是調(diào)用next()方法。

代碼在MessageQueue.java
307行

    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.
        // 如果消息循環(huán)已經(jīng)退出了。則直接在這里return。因?yàn)檎{(diào)用disposed()方法后mPtr=0
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }
        //記錄空閑時(shí)處理的IdlerHandler的數(shù)量
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        // native層用到的變量 ,如果消息尚未到達(dá)處理時(shí)間,則表示為距離該消息處理事件的總時(shí)長(zhǎng),
        // 表明Native Looper只需要block到消息需要處理的時(shí)間就行了。 所以nextPollTimeoutMillis>0表示還有消息待處理
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                //刷新下Binder命令,一般在阻塞前調(diào)用
                Binder.flushPendingCommands();
            }
            // 調(diào)用native層進(jìn)行消息標(biāo)示,nextPollTimeoutMillis 為0立即返回,為-1則阻塞等待。
            nativePollOnce(ptr, nextPollTimeoutMillis);
            //加上同步鎖
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                // 獲取開機(jī)到現(xiàn)在的時(shí)間
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                // 獲取MessageQueue的鏈表表頭的第一個(gè)元素
                Message msg = mMessages;
                 // 判斷Message是否是障柵,如果是則執(zhí)行循環(huán),攔截所有同步消息,直到取到第一個(gè)異步消息為止
                if (msg != null && msg.target == null) {
                     // 如果能進(jìn)入這個(gè)if,則表面MessageQueue的第一個(gè)元素就是障柵(barrier)
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    // 循環(huán)遍歷出第一個(gè)異步消息,這段代碼可以看出障柵會(huì)攔截所有同步消息
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                       //如果msg==null或者msg是異步消息則退出循環(huán),msg==null則意味著已經(jīng)循環(huán)結(jié)束
                    } while (msg != null && !msg.isAsynchronous());
                }
                 // 判斷是否有可執(zhí)行的Message
                if (msg != null) {  
                    // 判斷該Mesage是否到了被執(zhí)行的時(shí)間。
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        // 當(dāng)Message還沒(méi)有到被執(zhí)行時(shí)間的時(shí)候,記錄下一次要執(zhí)行的Message的時(shí)間點(diǎn)
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Message的被執(zhí)行時(shí)間已到
                        // Got a message.
                        // 從隊(duì)列中取出該Message,并重新構(gòu)建原來(lái)隊(duì)列的鏈接
                        // 刺客說(shuō)明說(shuō)有消息,所以不能阻塞
                        mBlocked = false;
                        // 如果還有上一個(gè)元素
                        if (prevMsg != null) {
                            //上一個(gè)元素的next(越過(guò)自己)直接指向下一個(gè)元素
                            prevMsg.next = msg.next;
                        } else {
                           //如果沒(méi)有上一個(gè)元素,則說(shuō)明是消息隊(duì)列中的頭元素,直接讓第二個(gè)元素變成頭元素
                            mMessages = msg.next;
                        }
                        // 因?yàn)橐〕鰉sg,所以msg的next不能指向鏈表的任何元素,所以next要置為null
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        // 標(biāo)記該Message為正處于使用狀態(tài),然后返回Message
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    // 沒(méi)有任何可執(zhí)行的Message,重置時(shí)間
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                // 關(guān)閉消息隊(duì)列,返回null,通知Looper停止循環(huán)
                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.
                // 當(dāng)?shù)谝淮窝h(huán)的時(shí)候才會(huì)在空閑的時(shí)候去執(zhí)行IdleHandler,從代碼可以看出所謂的空閑狀態(tài)
                // 指的就是當(dāng)隊(duì)列中沒(méi)有任何可執(zhí)行的Message,這里的可執(zhí)行有兩要求,
                // 即該Message不會(huì)被障柵攔截,且Message.when到達(dá)了執(zhí)行時(shí)間點(diǎn)
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                
                // 這里是消息隊(duì)列阻塞( 死循環(huán)) 的重點(diǎn),消息隊(duì)列在阻塞的標(biāo)示是消息隊(duì)列中沒(méi)有任何消息,
                // 并且所有的 IdleHandler 都已經(jīng)執(zhí)行過(guò)一次了
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }
    
                // 初始化要被執(zhí)行的IdleHandler,最少4個(gè)
                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.
            // 開始循環(huán)執(zhí)行所有的IdleHandler,并且根據(jù)返回值判斷是否保留IdleHandler
            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.
            // 重點(diǎn)代碼,IdleHandler只會(huì)在消息隊(duì)列阻塞之前執(zhí)行一次,執(zhí)行之后改標(biāo)示設(shè)置為0,
            // 之后就不會(huì)再執(zhí)行,一直到下一次調(diào)用MessageQueue.next() 方法。
            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.
            // 當(dāng)執(zhí)行了IdleHandler 的 處理之后,會(huì)消耗一段時(shí)間,這時(shí)候消息隊(duì)列里的可能有消息已經(jīng)到達(dá) 
             // 可執(zhí)行時(shí)間,所以重置該變量回去重新檢查消息隊(duì)列。
            nextPollTimeoutMillis = 0;
        }
    }

總的來(lái)說(shuō)當(dāng)我們?cè)噲D產(chǎn)品從MessageQueue中獲取一個(gè)Message的時(shí)候,會(huì)分為以下幾步

  • 首先、MessageQueue會(huì)先判斷隊(duì)列中是否有障柵的存在,如果有的話,只會(huì)返回異步消息,否則就逐個(gè)返回。
  • 其次、當(dāng)MessageQueue沒(méi)有任何消息可以處理的時(shí)候,它會(huì)進(jìn)度阻塞狀態(tài)等待新的消息到來(lái)(無(wú)線循環(huán)),在阻塞之前它會(huì)執(zhí)行以便 IdleHandler,所謂的阻塞其實(shí)就是不斷的循環(huán)查看是否有新的消息進(jìn)入隊(duì)列中。
  • 再次、當(dāng)MessageQueue被關(guān)閉的時(shí)候,其成員變量mQuitting會(huì)被標(biāo)記為true,然后在Looper視圖從隊(duì)列中取出Message的時(shí)候返回null,而Message==null就是告訴Looper消息隊(duì)列已經(jīng)關(guān)閉,應(yīng)該停止循環(huán)了,這一點(diǎn)可以在Looper.loop()房源中看出。
  • 最后、如果大家細(xì)心一定會(huì)發(fā)現(xiàn),Handler線程里面實(shí)際上有兩個(gè)無(wú)線循環(huán)體,Looper循環(huán)體和MessageQueue循環(huán)體,真正阻塞的地方是MessageQueue的next()方法里。

這里有個(gè)難點(diǎn),我簡(jiǎn)單說(shuō)下

//****************  第一部分  ***************
                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;
                }
  • 第一種情況:第一部分主要是判斷鏈表的第一個(gè)元素是否是障柵,如果是障柵,則進(jìn)入if,內(nèi)部區(qū)域,然后進(jìn)行while循環(huán),如果在鏈表中有一個(gè)元素是異步的,則跳出循環(huán),然后進(jìn)入第二部分,其中第二部分就是取出這個(gè)異步消息
  • 第二種情況:沒(méi)進(jìn)入進(jìn)入第一部分的if,則說(shuō)明頭部元素不是障柵(barrier),則直接進(jìn)入第二部分,這時(shí)候取出的就是當(dāng)前的頭部元素。

PS:

nativePollOnce是阻塞操作,其中nextPollTimeoutMillis代表下一個(gè)消息到來(lái)前,需要等待的時(shí)長(zhǎng),當(dāng)nextPollTimeoutMillis=-1時(shí),表示消息隊(duì)列無(wú)消息,會(huì)一直等待下去。nativePollOnce()是在native做了大量的工作。

(三)、msg.target.dispatchMessage(msg);方法

我們知道這個(gè)方法其實(shí)是Handler的dispatchMessage(Message)方法,那我們就來(lái)詳細(xì)看下
代碼在Handler.java 93行

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //當(dāng)Message存在回調(diào)方法,回調(diào)msg.callback.run()方法;
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                //當(dāng)Handler存在Callback成員變量時(shí),回調(diào)方法handleMessage();
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //Handler自身的回調(diào)方法handleMessage()
            handleMessage(msg);
        }
    }

這個(gè)方法很簡(jiǎn)單就是二個(gè)條件,三種情況

  • 情況1:如果msg.callback 不為空,則執(zhí)行handleCallback(Message),而handleCallback(Message)的內(nèi)部最終調(diào)用的是message.callback.run();,所以最終是msg.callback.run()。
  • 情況2:如果msg.callback 為空,且mCallback不為空,則執(zhí)行mCallback.handleMessage(msg)。
  • 情況3:如果msg.callback 為空,且mCallback也為空,則執(zhí)行handleMessage()方法

這里我們可以看到,在分發(fā)消息時(shí)三個(gè)方法的優(yōu)先級(jí)分別如下:

  • Message的回調(diào)方法優(yōu)先級(jí)最高,即message.callback.run();
  • Handler的回調(diào)方法優(yōu)先級(jí)次之,即Handler.mCallback.handleMessage(msg);
  • Handler的默認(rèn)方法優(yōu)先級(jí)最低,即Handler.handleMessage(msg)。

對(duì)于很多情況下,消息分發(fā)后的處理情況是第3種情況,即Handler.handleMessage(),一般地往往是通過(guò)覆寫該方法從而實(shí)現(xiàn)自己的業(yè)務(wù)邏輯。

二、消息(Message)的移除

(一) Handler的消息移除

消息(Message)的移除,其實(shí)就是根據(jù)身份what、消息Runnable或msg.obj移除隊(duì)列中對(duì)應(yīng)的消息。例如發(fā)送msg,用同一個(gè)msg.what作為參數(shù)。所有方法最終調(diào)用MessageQueue.removeMessages,來(lái)進(jìn)行時(shí)機(jī)操作的。

代碼如下,因?yàn)椴粡?fù)雜,我就合并在一起了

// Handler.java
public final void removeCallbacks(Runnable r) {
    mQueue.removeMessages(this, r, null);
}

public final void removeCallbacks(Runnable r, Object token) {
    mQueue.removeMessages(this, r, token);
}

public final void removeMessages(int what) {
    mQueue.removeMessages(this, what, null);
}

public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

所以我們知道,Handler里面的刪除工作,其實(shí)本地都是調(diào)用MessageQueue來(lái)操作的。

下面我們就來(lái)看下MessageQueue是怎么操作的?

(二) MessageQueue的消息移除

MessageQueue的消息移除在其類類的方法如下:


MessageQueue的消息移除.png

一共有5個(gè)方法如下:

  • 移除方法1:void removeMessages(Handler , int , Object )
  • 移除方法2:void removeMessages(Handler, Runnable,Object)
  • 移除方法3:void removeCallbacksAndMessages(Handler, Object)
  • 移除方法4:void removeAllMessagesLocked()
  • 移除方法5:void removeAllFutureMessagesLocked()

那我們就依次講解下:

移除方法1:void removeMessages(Handler , int , Object )方法

從消息隊(duì)列中刪除所有符合指定條件的Message

代碼在MessageQueue.java 587行

  void removeMessages(Handler h, int what, Object object) {
        // 第1步
        if (h == null) {
            return;
        }
         // 第2步
        synchronized (this) {
           // 第3步
            Message p = mMessages;

            // Remove all messages at front.

          
            //第4步
            while (p != null && p.target == h && p.what == what
                   && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            //第5步
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && n.what == what
                        && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

上面的代碼大體可以分為5個(gè)步驟如下:

  • 第1步、,對(duì)傳遞進(jìn)來(lái)的Handler做非空判斷,如果傳遞進(jìn)來(lái)的Handler為空,則直接返回
  • 第2步、,加同步鎖
  • 第3步、,獲取消息隊(duì)列鏈表的頭元素
  • 第4步、,如果從消息隊(duì)列的頭部就有符合刪除條件的Message,就從頭開始遍歷刪除所有符合條件的Message,并不端更新mMessages指向的Message。
  • 第5步、,因?yàn)橛辛?strong>第4步、,前面的的情況不會(huì)發(fā)生,也就是我們不需要關(guān)心指向的問(wèn)題,現(xiàn)在處理的問(wèn)題就是刪除剩下的符合刪除條件的Message。

總結(jié)一下:

從消息隊(duì)列中刪除Message的操作也是遍歷消息隊(duì)列然后刪除所有符合條件的Message,但是這里有連個(gè)小細(xì)節(jié)需要注意,從代碼中可以看出刪除Message分為兩次操作,第一次是先判斷符合刪除條件的Message是不是從消息隊(duì)列的頭部就開始有了,這時(shí)候會(huì)設(shè)計(jì)修改mMessage指向的問(wèn)題,而mMessage代表的就是整個(gè)消息隊(duì)列,在排除了第一種情況之后,剩下的就是繼續(xù)遍歷隊(duì)列刪除剩余的符合刪除條件的Message。其他重載方法也是同樣的操作,唯一條件就是條件不同而已,

移除方法2:void removeMessages(Handler, Runnable,Object)方法

從消息隊(duì)列中刪除所有符合指定條件的Message

代碼在MessageQueue.java 604行


    void removeMessages(Handler h, Runnable r, Object object) {
        if (h == null || r == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h && p.callback == r
                   && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && n.callback == r
                        && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

里面代碼和移除方法1:void removeMessages(Handler , int , Object )基本一致,唯一不同就是篩選條件不同而已。

移除方法3:void removeMessages(Handler, Runnable,Object)方法

從消息隊(duì)列中刪除所有符合指定條件的Message

代碼在MessageQueue.java 689行

    void removeCallbacksAndMessages(Handler h, Object object) {
        if (h == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h
                    && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

里面代碼和移除方法1:void removeMessages(Handler , int , Object )基本一致,唯一不同就是篩選條件不同而已。

移除方法4:void removeAllMessagesLocked()方法

刪除所有的消息

代碼在MessageQueue.java 722行

   private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

這個(gè)方法很簡(jiǎn)單,就是刪除所有的消息

移除方法5:void removeAllFutureMessagesLocked()

刪除所有未來(lái)消息

代碼在MessageQueue.java 732行

    private void removeAllFutureMessagesLocked() {
         // 第1步
        final long now = SystemClock.uptimeMillis();
         // 第2步
        Message p = mMessages;
        if (p != null) {
            // 第3步
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                // 第4步
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
               // 第5步
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }

這個(gè)方法大體上分為5個(gè)步驟,具體解釋如下:

  • 第1步:獲取當(dāng)前時(shí)間(其實(shí)從手機(jī)開機(jī)到現(xiàn)在的時(shí)間)
  • 第2步:獲取消息隊(duì)列鏈表的的頭元素
  • 第3步:如果頭元素的執(zhí)行的時(shí)間就大于當(dāng)前時(shí)間,因?yàn)槲覀冎梨湵淼呐判蚱鋵?shí)有從當(dāng)前到未來(lái)的順序排列的,所以但如果頭元素大于當(dāng)前時(shí)間,意味著這個(gè)鏈表的所有元素的執(zhí)行時(shí)間都大于當(dāng)前,則刪除鏈表中的全部元素。
  • 第4步:如果消息隊(duì)列中的頭元素小于或等于當(dāng)前時(shí)間,則說(shuō)明要從消息隊(duì)列中截取,從中間的某個(gè)未知的位置截取到消息隊(duì)列鏈表的隊(duì)尾。這個(gè)時(shí)候就需要找到這個(gè)具體的位置,這個(gè)步驟主要就是做這個(gè)事情。通過(guò)對(duì)比時(shí)間,找到合適的位置
  • 第5步:找到合適的位置后,就開始刪除這個(gè)位置到消息隊(duì)列隊(duì)尾的所有元素

三、關(guān)閉消息隊(duì)列

通過(guò)前面的文章,我們知道Handler消息機(jī)制的停止,本質(zhì)上是停止Looper的循環(huán),在Android Handler機(jī)制4之Looper與Handler簡(jiǎn)介文章中我們知道Looper的停止實(shí)際上是關(guān)閉消息隊(duì)列的關(guān)閉,現(xiàn)在我們來(lái)揭示MessageQueue是如何關(guān)閉的

代碼在MessageQueue.java 413行

    void quit(boolean safe) {
         // 第1步
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }
        // 第2步
        synchronized (this) {
            // 第3步
            if (mQuitting) {
                return;
            }
            mQuitting = true;
            // 第4步
            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

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

這個(gè)方法內(nèi)部大概分為5個(gè)步驟

  • 第1步:判斷是否允許退出,因?yàn)樵跇?gòu)造MessageQueue對(duì)象的時(shí)候傳入了一個(gè)boolean參數(shù),來(lái)表示該MessageQueue是否允許退出。而這個(gè)boolean參數(shù)在Looper里面設(shè)置,Loooper.prepare()方法里面是true,在Looper.prepareMainLooper()是false,由此可見我們知道:主線程的MessageQueue是不能退出。其他工作線程的MessageQueue是可以退出的。
  • 第2步:加上同步鎖
  • 第3步:主要防止重復(fù)退出,加入一個(gè)mQuitting變量表示是否退出
  • 第4步:如果該方法的變量safe為true,則刪除以當(dāng)前時(shí)間為分界線,刪除未來(lái)的所有消息,如果該方法的變量safe為false,則刪除當(dāng)前消息隊(duì)列的所有消息。
  • 第5步:刪除小時(shí)后nativeWake函數(shù),以觸發(fā)nativePollOnce函數(shù),結(jié)束等待,這個(gè)塊內(nèi)容請(qǐng)?jiān)?a href="" target="_blank">Android Handler機(jī)制9之Native的實(shí)現(xiàn)中,這里就不詳細(xì)描述了

四、查看消息是否存在

Handler機(jī)制也存在查找是否存在某條消息的機(jī)制,代碼如下:

// Handler.java
public final boolean hasMessages(int what) {
    return mQueue.hasMessages(this, what, null);
}

public final boolean hasMessages(int what, Object object) {
    return mQueue.hasMessages(this, what, object);
}

public final boolean hasCallbacks(Runnable r) {
    return mQueue.hasMessages(this, r, null);
}

我們發(fā)現(xiàn)其內(nèi)部都是調(diào)用MessageQueue的hasMessages函數(shù),那我們就來(lái)看下

(一) boolean hasMessages(Handler h, int what, Object object) 方法

代碼在MessageQueue.java 587行

    boolean hasMessages(Handler h, int what, Object object) {
        //第1步
        if (h == null) {
            return false;
        }
        //第2步
        synchronized (this) {
            //第3步
            Message p = mMessages;
            //第4步
            while (p != null) {
                if (p.target == h && p.what == what && (object == null || p.obj == object)) {
                    return true;
                }
                p = p.next;
            }
            return false;
        }
    }

該方法的主要內(nèi)容可以分為4個(gè)步驟

  • 第1步:判斷傳入進(jìn)來(lái)的Handler是否為空,如果傳入的Handler為空,直接返回false,表示沒(méi)有找到
  • 第2步:加上同步鎖
  • 第3步:取出消息隊(duì)列鏈表中的頭部元素
  • 第4步:遍歷消息隊(duì)里鏈表中的所有元素,如果有元素消息符合指定條件則return false,如果遍歷完畢還沒(méi)有則返回false

boolean hasMessages(Handler h, Runnable r, Object object)方法和本方法基本一致,唯一不同就是篩選條件不同而已。我就說(shuō)講解了。

五、阻塞非安全執(zhí)行

如果當(dāng)前執(zhí)行線程是Handler的線程,Runnable會(huì)被立刻執(zhí)行。否則把它放在消息隊(duì)列中一直等待執(zhí)行完畢或者超時(shí),超時(shí)后這個(gè)任務(wù)還在隊(duì)列中,在后面的某個(gè)時(shí)刻它仍然會(huì)執(zhí)行,很有可能造成死鎖,所以盡量不要用它。

這個(gè)方法使用場(chǎng)景是Android初始化一個(gè)WindowManagerService,應(yīng)為WindowManagerService不成功,其他組件就不允許繼續(xù),所以使用阻塞的方式直到完成。
代碼在Handler.java 461行


    /**
     * Runs the specified task synchronously.
     * <p>
     * If the current thread is the same as the handler thread, then the runnable
     * runs immediately without being enqueued.  Otherwise, posts the runnable
     * to the handler and waits for it to complete before returning.
     * </p><p>
     * This method is dangerous!  Improper use can result in deadlocks.
     * Never call this method while any locks are held or use it in a
     * possibly re-entrant manner.
     * </p><p>
     * This method is occasionally useful in situations where a background thread
     * must synchronously await completion of a task that must run on the
     * handler's thread.  However, this problem is often a symptom of bad design.
     * Consider improving the design (if possible) before resorting to this method.
     * </p><p>
     * One example of where you might want to use this method is when you just
     * set up a Handler thread and need to perform some initialization steps on
     * it before continuing execution.
     * </p><p>
     * If timeout occurs then this method returns <code>false</code> but the runnable
     * will remain posted on the handler and may already be in progress or
     * complete at a later time.
     * </p><p>
     * When using this method, be sure to use {@link Looper#quitSafely} when
     * quitting the looper.  Otherwise {@link #runWithScissors} may hang indefinitely.
     * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
     * </p>
     *
     * @param r The Runnable that will be executed synchronously.
     * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
     *
     * @return Returns true if the Runnable was successfully executed.
     *         Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     *
     * @hide This method is prone to abuse and should probably not be in the API.
     * If we ever do make it part of the API, we might want to rename it to something
     * less funny like runUnsafe().
     */
    public final boolean runWithScissors(final Runnable r, long timeout) {
         // 第1步
        if (r == null) {
            throw new IllegalArgumentException("runnable must not be null");
        }
         // 第2步
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout must be non-negative");
        }

          // 第3步
         // 如果為同一個(gè)線程,則直接執(zhí)行runnable,而不需要加入到消息隊(duì)列。
        if (Looper.myLooper() == mLooper) {
            r.run();
            return true;
        }
 
        // 第4步
        BlockingRunnable br = new BlockingRunnable(r);
        return br.postAndWait(this, timeout);
    }

首先先簡(jiǎn)單翻譯一下注釋:

  • 同步運(yùn)行指定的任務(wù)。
  • 如果當(dāng)前線程就是Handler的處理線程,則可以不用排隊(duì),直接運(yùn)行這個(gè)runnable。否則如果當(dāng)前線程和Handler的處理編程不是同一個(gè)線程則需要發(fā)送這個(gè)runnable到Handler線程,并且等待它完成后再返回。
  • 使用這個(gè)方法是有風(fēng)險(xiǎn)的,使用不當(dāng)可能會(huì)導(dǎo)致死鎖。不要在有鎖或者可能有鎖的代碼區(qū)域調(diào)用這個(gè)方法。
  • 這個(gè)方法的使用場(chǎng)景通常是,一個(gè)后臺(tái)線程必須等待Handler線程中的一個(gè)任務(wù)的完成。但是,這往往是不優(yōu)雅設(shè)計(jì)才會(huì)出現(xiàn)的問(wèn)題。所以在使用這個(gè)方法的時(shí)候,請(qǐng)首先考慮改進(jìn)設(shè)計(jì)方案。
  • 這個(gè)方法的使用場(chǎng)景是:在你建立Handler線程之前,你需要執(zhí)行一些初始化操作。
  • 如果發(fā)生超時(shí),雖然該方法還是會(huì)返回false,但是該
    如果超時(shí)發(fā)生,那么該方法返回<code> false </ code>,但是runnable仍是會(huì)保留在Handler中,并且在一段時(shí)間以后會(huì)在被執(zhí)行。
  • 在使用這個(gè)方法的時(shí)候,并且要退出一個(gè)Looper的時(shí)候,請(qǐng)一定要調(diào)用quitSafely()這個(gè)方法。否則runWithScissors()這個(gè)方法可能會(huì)無(wú)限期掛起。(TODO:我們應(yīng)該通知MessageQueue去阻止runnable來(lái)解決這個(gè)問(wèn)題)

該方法內(nèi)部的執(zhí)行流程主要分為4個(gè)步驟,如下:

  • 第1步、:Runnable非空判斷
  • 第2步、:timeout是否小于0判斷
  • 第3步、:如果Looper的線程和Handler的線程是同一個(gè)線程
  • 第4步、,構(gòu)造一個(gè)BlockingRunnable對(duì)象,并調(diào)用該對(duì)象的postAndWait(Handler,long)方法

上面涉及到一個(gè)咱們之前沒(méi)有講解過(guò)的類:BlockingRunnable,他是Handler的靜態(tài)內(nèi)部類,我們來(lái)研究下

(一)、Handler的靜態(tài)內(nèi)部類BlockingRunnable

BlockingRunnable是Handler的一個(gè)私有內(nèi)部靜態(tài)類,利用Object的wait和notifyAll方法實(shí)現(xiàn)。

代碼在Handler.java

  private static final class BlockingRunnable implements Runnable {
        private final Runnable mTask;
        private boolean mDone;

        public BlockingRunnable(Runnable task) {
            mTask = task;
        }

        @Override
        public void run() {
            try {
                mTask.run();
            } finally {
                synchronized (this) {
                    mDone = true;
                     // runnable 執(zhí)行完之后,會(huì)通知wait的線程不再wait
                    notifyAll();
                }
            }
        }

        public boolean postAndWait(Handler handler, long timeout) {
            if (!handler.post(this)) {
                return false;
            }

            synchronized (this) {
                if (timeout > 0) {
                    final long expirationTime = SystemClock.uptimeMillis() + timeout;
                    while (!mDone) {
                        long delay = expirationTime - SystemClock.uptimeMillis();
                        if (delay <= 0) {
                            return false; // timeout
                        }
                       // post runnable 之后,將調(diào)用線程變?yōu)閣ait狀態(tài)
                        try {
                            wait(delay);
                        } catch (InterruptedException ex) {
                        }
                    }
                } else {
                    while (!mDone) {
                         // post runnable 之后,將調(diào)用線程變?yōu)閣ait狀態(tài)
                        try {
                            wait();
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            }
            return true;
        }
    }

通過(guò)分析源碼我們獲取的了如下信息:

  • 1、該類實(shí)現(xiàn)了Runnable接口
  • 2、構(gòu)造函數(shù):接受一個(gè)Runnable作為參數(shù)的構(gòu)造函數(shù),包含了真正要執(zhí)行的Task。
  • 3、run函數(shù)很簡(jiǎn)單,直接調(diào)用mTask.run(),一個(gè)finally內(nèi)會(huì)同步對(duì)象本身(因?yàn)閙Done涉及到多線程,而notifyAll()則需要synchronized配合)
  • 4、postAndWait(Handler, long):首先嘗試將BlockingRunnable自己post到handler上,如果post失敗,則直接返回false;其次如果上一步的post成功,就需要同步對(duì)象本身(為了使用wait());此時(shí),如果timeout>0,那么就一個(gè)while循環(huán)+wait(long),中間有任何的interrupt都直接catch重新結(jié)算wait的時(shí)間,只有在任務(wù)完成(mDone=true,另外線程的run函數(shù)會(huì)設(shè)置此值)或者任何超時(shí)才會(huì)返回(true/false);如果imeout <=0,也就無(wú)限等待了
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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