看源碼分析Handler的執(zhí)行流程

記得之前面試時,面試官就問了Handler的工作流程,當時腦子里有MessageQueue、Looper等類名但具體怎么執(zhí)行的卻說不明白。于是乎面試也就失敗了。想想還是挺菜雞的。。以一個簡單的例子通過源碼來走一遍Handler的執(zhí)行流程。

Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });


  protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        Message message=Message.obtain();
        message.arg1=1;
        handler.sendMessage(message);
 }

1.MessageQueue

就是這么一個最簡單的例子先進入sendMessage方法,然后又跳到了sendMessageDelayed方法,最后跳到了sendMessageAtTime方法,在sendMessageAtTime方法中看到了熟悉的面孔MessageQueue,初始化了一下MessageQueue,之后進入了enqueueMessage方法。

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

enqueueMessage方法:

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


boolean 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(TAG, 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;
    }

在enqueueMessage方法中將msg.target設置為當前的Handler,也就是綁定了Handler,然后進入enqueueMessage中,通過模擬代碼執(zhí)行,有了一個重要的結論,我們每發(fā)送一個消息都被保存到了 MessageQueue 消息隊列中,消息隊列中采用的是單鏈表的方式。

// 發(fā)送 Message1
Message message1 = new Message();
mHandler.sendMessageDelayed(message1, 500);

// 發(fā)送 Message2
Message message2 = new Message();
mHandler.sendMessage(message2);

// 發(fā)送 Message3
Message message3 = new Message();
mHandler.sendMessageDelayed(message3, 1000);

主要看這段來模擬:

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

模擬如下:

message1.when=500;
Message p = mMessages;
而mMessages=null; 所以Message p =null;
因為p =null,所以進入if
message1.next = null;
mMessages = message1;

所以發(fā)送完message1之后鏈表應該是這樣的:
發(fā)送完message1

然后發(fā)送message2:

message2.when=0;
Message p = mMessages; //在發(fā)送message1是已經(jīng)將mMessages賦值為 message1
所以
p=message1;
 if (p == null || when == 0 || when < p.when) 
因為when=0,所以進入if
message2.next=p;即
message2.next=message1
mMessages =message2;

所以發(fā)送完message2之后鏈表應該是這樣的:
發(fā)送完message2

然后發(fā)送message2:

message3.when=1000;
Message p =message2;
 if (p == null || when == 0 || when < p.when)  不滿足if條件,進入else
  Message prev;
進入for(;;)循環(huán)
prev = message2;
p = p.next;即
p=message1;
 if (p == null || when < p.when) //  不滿足if繼續(xù)循環(huán)
 prev = p;
 即
prev = message1;
p = p.next;即   
p=null;
if (p == null || when < p.when) // 滿足條件進入if 跳出
msg.next = p;即
message3.next=null;
prev.next = msg; 即
message1.next=message3                  
         

所以發(fā)送完message3之后應該是這樣的:


發(fā)送完message3

得出結論消息在隊列中是按when和先后順序排列的。

2. Loop 消息循環(huán)

我們始終沒有看到 Handler 調(diào)用 handleMessage() 方法,到底什么時候會執(zhí)行這個方法?
書上說在子線程中使用handler要先

 Looper.prepare();
 Handler handler = new Handler();
 Looper.loop();

否則會報錯,而在MainActivity即主線程中直接使用不會報錯。原因就是在啟動Activity過程中在ActivityThread幫我們已經(jīng)調(diào)用過了代碼如下:

 ActivityThread.java main()
 public static void main(String[] args) {
        ....

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }


public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }


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

public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

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

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
 }

在prepare(false)方法中創(chuàng)建一個Looper對象并把它存儲到sThreadLocal中并且與當前線程綁定。
當調(diào)用 loop()方法再在從sThreadLocal中取出Looper對象。ThreadLocal用來保證一個線程只有一個 Looper 對象,這樣就保證了線程的安全。接下來是一個for(;;)死循環(huán)調(diào)用隊列中msg.target.dispatchMessage。這樣就找到了在handleMessage中可以收到信息的原因。message的target是在加入隊列時設置的。

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

總結:Looper.prepareMainLooper() 創(chuàng)建了一個 Looper 對象,而且保證一個線程只有一個 Looper;Looper.loop() 里面是一個死循環(huán),不斷的從 消息隊列 MessageQueue 中取消息,然后通過 Handler 執(zhí)行。

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

  • 小城一角
    陌上花開一水間閱讀 924評論 0 2
  • 文/船長 7:54 今天堅持日更第11天了。堅持寫作這件事,為了遇見最好的自己。 我給自己定下的目標是,堅持每天禪...
    一心船長閱讀 1,038評論 5 12
  • 我想要改變,變成一個讓父母驕傲、讓朋友依靠的人!可是事實總是不如人意~大學還沒畢業(yè)父母就安排的一份安穩(wěn)的工作,每天...
    一束陽光的顏顏姑娘閱讀 241評論 0 1
  • 身體是心靈的一面鏡子,它會如實地儲存我們過往的所有經(jīng)驗,并且將那些無處宣泄的情緒,無法表達的感受,全部以“病痛”這...
    月清清閱讀 1,019評論 0 0

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