Android消息機制三劍客之Handler、Looper、Message源碼分析(二)

Android消息機制:
Android消息機制三劍客之Handler、Looper、Message源碼分析(一)
Android消息機制三劍客之Handler、Looper、Message源碼分析(二)

消息通信機制的運行原理

    上一篇中,單獨分析了Handler、Looper、MessageQueue,本篇就分析一下這三者是如何協同工作,實現線程間通信的。我們就以Looper類中官方給出的子線程中經典通信樣例來分析分析每步都做了什麼。

  *  class LooperThread extends Thread {
  *      public Handler mHandler;
  *
  *      public void run() {
  *          Looper.prepare();
  *
  *          mHandler = new Handler() {
  *              public void handleMessage(Message msg) {
  *                  // process incoming messages here
  *              }
  *          };
  *
  *          Looper.loop();
  *      }
  *  

    首先,在線程中先調用了Looper.prepare():

    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);
        mRun = true;
        mThread = Thread.currentThread();
    }

    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        nativeInit();
    }

    prepare方法爲當前線程初始化通信環境,每個線程只能持有一個Looper實例,並且通過set將Looper實例與本地線程綁定。而在Lopper的構造函數中,又創建了MessageQueue的實例,這裏也就爲當前線程準備好了MessageQueue來接收Message對象,而在MessageQueue的構造函數中調用的是Native層的初始化方法,創建一個單向鏈表的隊列,對Native層有興趣的朋友可以自行分析,這裏就不再深入了。
    接下來mHandler = new Handler() {…}創建了Handler的實例,並重寫了handleMessage,也就是消息通信的終點,那麼我們來看看Handler的構造方法:

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

   //空構造最終調用了下面的構造方法

   /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with represent to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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是不是同步的? 當時一下懵住了,沒有想過這個問題,但答案其實在註釋裏已經告訴我們了,這裏就不再對註釋進行翻譯,大家可以自行看一下。在Handler的構造方法裏可以看到分別拿到了Looper和Message的實例,mLooper和mQueue,在這裏三劍客也就聚齊了。
    運行到這裏,當前線程下的消息通信環境已經搭建完成,接下來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();
        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.recycle();
        }
    }

    loop()方法中核心就是開啓了無限循環,這其中,我們需要仔細研究的是這三個關鍵方法:

  • queue.next():從MessageQueue中取出下一個Message,在MessageQueue中執行一次出隊操作;
  • msg.target.dispatchMessage(msg) :將取出的Message對象分發給綁定的Handler;
  • msg.recycle() : 回收該Message實例,存入global pool,後續可以通過msg.obtain()在global pool中直接獲取Message實例,避免了每次都創建新的實例;

     首先看一下next()方法的內部實現:

final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);

            synchronized (this) {
                if (mQuiting) {
                    return null;
                }

                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;      /** mMessage是該鏈表隊列的頭結點 **/
                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);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
                // 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;
                }

            ... ...

           }//(sync)
        }//(for)
    }

     next()方法中核心邏輯也是一個無限循環,目的就是返回下一個要處理的消息,然後從消息隊列中進行出隊。其中mMessages保存的是隊列的頭結點,從該節點開始向下遍歷。首先進行判空處理,在msg非空但target爲空時表示這是一個異步消息,是否異步是在Handler構造時進行定義的,默認情況下都是同步的,因此這裏的邏輯一般不會執行。
    接着向下,判斷當前時間是否到達msg指定的發送時間,因爲消息入隊時會根據攜帶的發送時間進行排序,在未達到發送時間時,msg不出隊,而是設置nextPollTimeoutMillis,這個變量有什麼用呢,我們回到循環最開始的地方,這裏在nextPollTimeoutMillis 非0時,調用flushPendingCommands掛起當前線程,該方法預示系統後續可能會有長時間的線程block到來,也就是最後一部分,在當前線程掛起(兩種情況:初始消息隊列爲空 或 msg需要在未來某時處理)後會取出idelHandler(閒置Handler,如果存在的話)進行處理。如果這時候連idelHandler也不存在的話,線程進入阻塞,continue直接無限循環,直到找到需要處理的msg。
    那麼找到msg後,因爲默認都是同步msg,這裏prevMsg爲空,走else,將mMessage頭結點指針向下移動,然後msg出隊,添加已用標記,return返回msg,這樣Looper.loop()方法中的Message msg = queue.next()這條語句執行完畢 ,拿到要進行分發的Message對象,那麼接下來就是執行msg.target.dispatchMessage(msg); 進行消息分發,這裏調用到的是Handler中的方法:

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    dispatchMessage方法很簡單,我們在創建Handler實例的時候使用的空構造,因此這裏的callback爲null,也就是直接調用了handleMessage,也就是在創建時候我們重寫的handleMessage方法了,至此消息得到處理,Message對象完成了一次通信,在loop()中最後調用recycle()方法,將Message實例回收,可以通過obtain再次獲取到該實例,而不必每次都新建實例了。
    至此,我們通過一個官方簡單示例分析了整個消息通信的框架,現在我們再根據流程圖總體回顧一下:
這裏寫圖片描述
    在本地線程中,首先必須先調用Looper.prepare()方法,該方法會創建號Looper實例和MessageQueue實例,然後再創建Hanlder實例,並重寫handlerMessage方法,自定義消息處理,在Handler的構造方法中,會引入Looper和MessageQueue實例。然後調用Looper.loop()開啓無限循環,不斷的調用next()從消息隊列中取出消息,如果消息隊列爲空或未到消息處理時間時,線程進入阻塞狀態。而在外部,調用Handler的send/post系列方法後,最終都調用SendMessageAtTime方法,爲msg添加when屬性,然後調用Handler內部的enqueueMessage方法,此處爲msd綁定target爲當前Handler,接着調用到MessageQueue類中定義的enqueueMessage,此方法中將接收的msg進行入隊,將mMessages指向隊列頭部。同時,入隊操作還會喚醒已阻塞的線程(如果在阻塞狀態的話),接着next()方法就可以取到該入隊的msg,並調用msg.target.dispatchMessage()方法,最後就調用到了重寫的handleMessage()方法,完成了消息通信。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章