Android HandlerThread 訊息迴圈機制之源碼解析

來源:互聯網
上載者:User

Android HandlerThread 訊息迴圈機制之源碼解析

關於 HandlerThread 這個類,可能有些人眼睛一瞟,手指放在鍵盤上,然後就是一陣狂敲,馬上就能敲出一段段華麗的代碼:

HandlerThread handlerThread = new HandlerThread("handlerThread");handlerThread.start();Handler handler = new Handler(handlerThread.getLooper()){    public void handleMessage(Message msg) {        ...    }};handler.sendMessage(***);

仔細一看,沒問題啊(我也沒說代碼有問題啊),那請容許我說一句,“這代碼敲也敲完了,原理懂不?”

為什麼要扯這玩意,沒什麼理由,就是不小心看了這篇文章Android訊息迴圈機制源碼分析。學姐說了,源碼都沒看,沒分析,還敢說你懂。原本還覺得自己懂了點,看完這句話,頓時就不確定了。於是,自覺開啟了 AS …

前言

首先,先給各位看官打個預防針,待會要講的東西可能有點多,有點繞,涉及的類包含有:HandlerThread、Thread、Handler、Looper、Message、MessageQueue,可能有些人已經遭不住啦,有種想要關閉網頁的衝動。不要慌,剛開始我看源碼的時候我也不知道最終會牽扯這麼一大串出來,但仔細理一理後,其實就是那麼回事。

一、擒賊先擒王 HandlerThread

這件事情的源頭都是因它而起的,不先找它先找誰。

首先,HandlerThread 是什麼gui,感覺像是 Handler 和 Thread 的結合體。點進源碼一看:public class HandlerThread extends Thread {} 沒什麼好說的,原來是一個線程的子類。那麼接下來就要看看這個 HandlerThread 到底有什麼特殊之處。

HandlerThread handlerThread = new HandlerThread("handlerThread");handlerThread.start();

跟正常線程的建立、啟動步驟一樣,線程已啟動,那勢必會執行其 run() 方法。為了方便下面流程的分析,這裡先用代碼塊1表示:

#HandlerThread.javapublic void run() {    mTid = Process.myTid();    Looper.prepare();    synchronized (this) {        mLooper = Looper.myLooper();        notifyAll();    }    Process.setThreadPriority(mPriority);    onLooperPrepared();    Looper.loop();    mTid = -1;}

其中,Looper 就代表我們經常說的訊息迴圈,Looper.prepare() 就代表訊息迴圈執行前的一些準備工作。

二、抓捕各種小弟(Looper、MessageQueue、Message)

既然上面已經談到Looper,那就來看一下它的幾個方法:Looper.prepare() 和 Looper.loop()。
代碼塊2

#Looper.javapublic 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();}static final ThreadLocal sThreadLocal = new ThreadLocal();final MessageQueue mQueue;final Thread mThread;

上面一路下來還是挺清晰的,總結一下:因為一個 Thread 只能對應有一個 Looper,所以只有滿足條件下才會將 Looper 對象存放在類型為 ThreadLocal 的類屬性裡。當然在這之前還是要先 new 一個 Looper 對象,而在 Looper 的構造方法中又建立了兩個對象 ,分別為mQueue(訊息佇列)和 mThread(當前線程)。整個 prepare 過程其實主要是建立了三個對象:Looper、MessageQueue、Thread。
好了,Looper.prepare() 這個過程已經分析完了。接著我們再看代碼塊1,裡面有一段同步代碼塊,目的是為了擷取 Looper 對象。方法跳轉過去一看,原來就是將之前存進 ThreadLocal 裡的Looper 對象取出 。

#Looper.javapublic static Looper myLooper() {    return sThreadLocal.get();}

接下來最關鍵的就是 Looper.loop() 這句代碼,它也是 HandlerThread 這個類存在的價值所在。只要一執行這句代碼,也就代表真正的訊息迴圈開始啦:代碼塊3

#Looper.javapublic 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        Printer logging = me.mLogging;        if (logging != null) {            logging.println(">>>>> Dispatching to " + msg.target + " " +                    msg.callback + ": " + msg.what);        }        msg.target.dispatchMessage(msg);        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();    }}

這個方法的作用就是開始從訊息佇列中迴圈取出訊息。那這個訊息佇列又從哪來的呢,還記得我們在Looper.prepare() 中建立 Looper 對象的時候在其構造方法中 new 兩個對象嘛,一個 MessageQueue,一個Thread。在這裡要想使用訊息佇列,首先需要先擷取 Looper 執行個體,畢竟訊息佇列 MessageQueue 是作為其成員屬性而存在的;接著獲得了訊息佇列的對象,並進入一個貌似死迴圈的控制流程中。這個 for 語句乾的事情就是不斷的從訊息佇列 MessageQueue 裡取出訊息,然後發送出去。具體誰來處理這些訊息馬上揭曉。下面的代碼就是從訊息佇列中取出訊息:

#Looper.javaMessage msg = queue.next()

接下去的內容可能就需要各位看官對資料結構有點瞭解了,我們一步一步嵌進去看一下。代碼塊4

#MessageQueue.javaMessage next() {    ...    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 (false) Log.v("MessageQueue", "Returning message: " + msg);                    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);        }        ...    }}

其它可以先不管,我們直接跳轉到 synchronized 這同步代碼塊裡。我們看到Message msg = mMessage; 這個 mMessage 對象就是一個訊息 Message,只不過這個 Message 類裡面附帶了一種資料結構:隊列。我們不妨看一下這個類:

public final class Message implements Parcelable {    ...    // sometimes we store linked lists of these things    /*package*/ Message next;       ...}

不難看出,Message 類中包含了一個 Message 類型的屬性,作用就是指向下一條訊息,依次類推,最終形成一個訊息佇列。只不過這裡隊列中的訊息是要經過特殊處理的,並不是每進來一條訊息就直接添加在隊列尾部。因為 Android 系統中的訊息是有時間機制的,每條訊息都會附加一個時間,這也是handler.sendMessageDelayed() 存在的意義。

接著看代碼塊4,先是對 msg 和 msg.target 進行判斷,只要訊息佇列中的訊息不為空白,同時出對的訊息的觸發時間小於當前系統的時間,那麼這個訊息就回被取出來作為待發送的對象。這裡 msg.target 是非常重要的,我們之所以能 handleMessage 全靠它,下面會分析到。

然後回到代碼塊3,通過

Message msg = queue.next(); // might block

拿到訊息後,再由 msg.target 將訊息分發出去

msg.target.dispatchMessage(msg);

那這個 msg.target 到底是個什麼東西。看屬性定義

/*package*/ Handler target;

居然是一個 Handler,通過它將訊息分發出去,我們再看一下是怎樣分發的:

#Handler.java/** * 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);    }}

是不是有種茅塞頓開的感覺。在這我就直接透漏一下,Message 中的 callback 其實就是一個 Runnable 對象,handleCallback(msg); 就是執行其 run() 方法。這也是為什麼我們可以通過 handler.post(new Runnable(){...})來發送訊息,其實就是把Runnable對象賦給了Message的Callback 屬性。而如果是正常的 handler.sendMessage(),那麼肯定就是執行下面的語句咯。我們可以在建立 Handler 對象的時候指定一個回調介面 Callback。當然不指定也沒事,我們最終還是可以通過 handleMessage(msg) 來擷取待處理的訊息。最後,我們還是要對這條訊息進行回收重用的嘛msg.recycleUnchecked();

好了,關於Looper.prepare() 和 Looper.loop() 這兩個方法就介紹到這。我們再來補充一下,訊息佇列之所以有訊息,那肯定得有誰提供瑟。答案就是 Handler。我們經常的操作就是handler.sendMessage(msg);,代碼塊5

#Handler.javapublic final boolean sendMessage(Message msg) {    return sendMessageDelayed(msg, 0);}public final boolean sendMessageDelayed(Message msg, long delayMillis){    if (delayMillis < 0) {        delayMillis = 0;    }    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);}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);}private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {    msg.target = this;    if (mAsynchronous) {        msg.setAsynchronous(true);    }    return queue.enqueueMessage(msg, uptimeMillis);}
#MessageQueue.javaboolean 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("MessageQueue", e.getMessage(), e);            msg.recycle();            return false;        }        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 進行封裝,什麼 msg.when、msg.target,通通在這裡搞定。現在仔細回想 Looper.loop() 裡面對 msg 的處理,之前的各種?是不就煙消雲散啦。後面就頂多就是將訊息入隊,入隊前就如我前面所說的那樣,要根據 msg.when 的時間進行入隊,然後插入到合適的位置中去。

總結

至此,整個訊息迴圈機制就分析完啦,原始代碼:

HandlerThread handlerThread = new HandlerThread("handlerThread");handlerThread.start();Handler handler = new Handler(handlerThread.getLooper()){    public void handleMessage(Message msg) {        ...    }};handler.sendMessage(***);

再看一下具體操作流程:

handlerThread.start() -> Looper.prepare() -> Looper.loop() -> queue.next() -> msg.target.dispatchMessage(msg) -> handleMessage(msg) handler.sendMessage(msg) -> queue.enqueueMessage(msg)

由於上面的一切操作都是在一個新線程的 run() 方法中執行,所以不會阻塞 UI 線程,分析完畢。
這時可能有些人就站出來了,這 HandlerThread 感覺也沒啥啊,我直接用 Thread 也可以搞定一切。設想一下,加入現在有10個背景工作需要執行,按照傳統的做法就是執行10遍 new Thread(某個Runnable對象).start() 首先你是建立了10個匿名對象,這資源消耗多少暫且不說,你還不能很好的控制它們,這樣很容易造成記憶體流失。若是將這些背景工作打包成成一個個 Message 然後再發送出去,首先是線程可以得到重用,再者我們還可以 remove 掉訊息佇列中的訊息,再一定程度上避免了記憶體流失。好了,該說的都說完了,可能需要各位看官自己腦補一下、消化一下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.