Android非同步訊息機制-深入理解Handler、Looper和MessageQueue之間的關係

Charming本尊發表於2017-10-14

Android非同步訊息機制-深入理解Handler、Looper和MessageQueue之間的關係

相信做安卓的很多人都遇到過這方面的問題,什麼是非同步訊息機制,什麼又是HandlerLooperMessageQueue,它們之間又有什麼關係?它們是如何協作來保證安卓app的正常執行?它們在開發中具體的使用場景是怎樣的?今天,就讓我們來揭開這幾個Android非同步訊息機制中重要角色的神祕面紗。

一、寫在前面

為什麼要學習Android非同步訊息機制?和AMS、WMS、View體系一樣,非同步訊息機制是Android framework層非常重要的知識點,掌握了對於日常開發、問題定位和解決都是非常有幫助的,會使的我們開發事半功倍。而要想成為一個合格的Android開發人員,光是懂得呼叫Android提供的那些個api是不夠的,還要學會分析這些api背後的原理,知道它們是如果工作的,做到知其然亦知其所以然,如果不去學習技術背後的原理,只流於表面,這樣永遠都不會有進步,永遠都只是一個Android菜鳥。

二、原始碼分析

1、主執行緒建立Looper

Android中主執行緒也就是我們所說的UI執行緒,可以簡單理解為所有的介面呈現,能看得到的操作,所有的觸控、點選螢幕、更新介面UI事件的處理,都是在主執行緒中完成的。一個執行緒只有一條執行路徑,如果主執行緒同時有多個事件要處理,那麼是怎麼做到有條不紊地處理的呢?接下來,以上提到的幾個角色就要登場了,就是Handler+Looper+MessageQueue這三個角色在起作用。

Looper是執行緒的訊息輪詢器,是整個訊息機制的核心,來看看主執行緒的Looper是如何建立的。

主執行緒開啟於 ActivityThreadmain 方法中,來看一下 main 方法的原始碼。

public static void main(String[] args) {

        、、、

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

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

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

        、、、
    }複製程式碼

Looper.prepareMainLooper() 這句程式碼似乎為主執行緒建立 Looper,進入方法內部一探究竟。

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));
    }複製程式碼

果然在這個方法內部又呼叫 Looper.prepare(boolean) 方法為主執行緒建立 Looper 物件,儲存在 ThreadLocal 中,我們都知道,ThreadLocal 為每個執行緒建立一個副本,所以不同執行緒 set 的值不會被覆蓋,再次取出值時對應的是該執行緒 set 進去的值。接下來通過 Looper.myLooper() 拿到主執行緒的 LooperLooper 的靜態變數sMainLooper持有,之後再想取主執行緒 Looper 通過 Looper.getMainLooper() 拿到

public static Looper getMainLooper() {
    synchronized (Looper.class) {
        return sMainLooper;
    }
}複製程式碼

這樣,主執行緒的Looper就建立成功了,需要注意的是,無論是主執行緒還是子執行緒,Looper只能被建立一次,否則會拋異常,以上原始碼可以很好地解釋。

2、子執行緒建立Looper

與主執行緒稍稍有點不一樣,子執行緒的Looper需要手動去建立,並且有些地方是需要注意的,下面讓我們一起來探究一下。

子執行緒建立Looper標準寫法是這樣的

new Thread(new Runnable() {
            @Override
            public void run() {
                //建立子執行緒的Looper
                Looper.prepare();
                //開啟訊息輪詢
                Looper.loop();
            }
        }).start();複製程式碼

需要先建立子執行緒的Looper再開啟訊息輪詢,否則Looper.loop()中會拋RuntimeException

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        、、、
    }複製程式碼

這樣,主執行緒和子執行緒的Looper建立過程我們都知道了,有了Looper,我們就能開啟訊息輪詢了嗎?不能,因為Looper只是訊息輪詢器,就好比大廚,還需要食材才能烹飪,因此要想開啟訊息輪詢,還需要訊息的倉庫,訊息佇列MessageQueue

3、MessageQueue的建立

我們看看Looper的私有構造方法

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}複製程式碼

可見在每個執行緒建立Looper的時候也建立了一個MessageQueue,並將MessageQueue物件作為該執行緒Looper的成員變數,這就是MessageQueue的建立過程。

4、開啟訊息輪詢

有了LooperMessageQueue之後就能開啟訊息輪詢了,非常簡單,通過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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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();
        }
    }複製程式碼

在方法中可以看到有一個for(;;)死迴圈,該迴圈中又呼叫了MessageQueuenext()方法 ,進入方法一探究竟。

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.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        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);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            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.
            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.
            nextPollTimeoutMillis = 0;
        }
    }複製程式碼

該方法裡面同樣有一個for(;;)死迴圈,當沒有可以處理該訊息的Handler時,就會一直阻塞

if (pendingIdleHandlerCount <= 0) {
    // No idle handlers to run.  Loop and wait some more.
    mBlocked = true;
    continue;
}複製程式碼

如果從MessageQueue中拿到訊息,返回Looper.loop()中,loop()有以下片段

try {
    msg.target.dispatchMessage(msg);
    end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
    if (traceTag != 0) {
        Trace.traceEnd(traceTag);
    }複製程式碼

可以很清楚看到Message是用它所繫結的Handler來處理的,呼叫dispatchMessage(Message),這個Handler其實就是傳送MessageMessageQueue時所用的Handler,在傳送時繫結了。

Handler拿到訊息之後會怎麼處理呢,我們暫且擱一邊,先來看看Handler是怎麼建立併傳送訊息的

5、建立Handler

可以繼承於Handler並重寫handleMessage(),實現自己處理訊息的邏輯

private static class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }複製程式碼

簡單地,可以在程式中這樣建立

MyHandler handler = new MyHandler();複製程式碼

需要注意的是,執行緒建立Handler例項之前必須先建立Looper例項,否則會拋RuntimeException

ublic 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的內部介面Callback來完成

public interface Callback {
    public boolean handleMessage(Message msg);
}複製程式碼
Handler handler = new Handler(new Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //處理訊息
                return true;
            }
        });複製程式碼

關於這兩種處理訊息的方式哪個優先順序更高,接下來會講到

6、Handler傳送訊息

首先可以通過類似以下的程式碼來建立Message

Message message = Message.obtain();
message.arg1 = 1;
message.arg2 = 2;
message.obj = new Object();複製程式碼

Handler傳送訊息的方式多種多樣,常見有這幾種

sendEmptyMessage();           //傳送空訊息
sendEmptyMessageAtTime();     //傳送按照指定時間處理的空訊息
sendEmptyMessageDelayed();    //傳送延遲指定時間處理的空訊息
sendMessage();                //傳送一條訊息
sendMessageAtTime();          //傳送按照指定時間處理的訊息
sendMessageDelayed();         //傳送延遲指定時間處理的訊息
sendMessageAtFrontOfQueue();  //將訊息傳送到訊息隊頭複製程式碼

也可以在設定Handler之後,通過message自身傳送訊息,不過最終都是呼叫Handler傳送訊息的方法

message.setTarget(handler);
message.sendToTarget();

public void sendToTarget() {
    target.sendMessage(this);
}複製程式碼

除此之外,還有一種另類的傳送方式

post();
postDelayed();
postAtTime();
postAtFrontOfQueue();複製程式碼

post(Runnable r)為例,此種方式是通過post一個Runnable回撥,構造成一個Message併傳送

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

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}複製程式碼

Runnable回撥儲存在Message的成員變數callback中,callback的作用,接下來會講到

以上是訊息的傳送方式,那麼訊息是如何傳送到MessageQueue的呢,再來看

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);
}複製程式碼

所有的訊息傳送方式最終都是呼叫 HandlersendMessageAtTime(),並且會檢查訊息佇列是否為空,若空則拋 RuntimeException,之後呼叫 HandlerenqueueMessage() ,最後呼叫MessageQueueenqueueMessage() 將訊息入隊。

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;
    }複製程式碼

該方法根據訊息的處理時間來對訊息進行排序,最終確定哪個訊息先被處理

至此,我們已經很清楚訊息的建立和傳送以及訊息輪詢過程了,最後來看看訊息是怎麼被處理的

7、訊息的處理

回到Looper.loop()中的這一句程式碼

msg.target.dispatchMessage(msg);複製程式碼

訊息被它所繫結的HandlerdispatchMessage()處理了

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

由此可見,訊息處理到底採用哪種方式,是有優先順序區分的

首先是post方法傳送的訊息,會呼叫Message中的callback,也就是Runnablerun()來處理

private static void handleCallback(Message message) {
    message.callback.run();
}複製程式碼

其次則是看Handler在建立時有沒有實現Callback回撥介面,若有,則呼叫

mCallback.handleMessage(msg)複製程式碼

如果該方法沒能力處理,則返回false,讓給接下來處理

最後才是呼叫HandlerhandleMessage()

三、總結

  1. 熟悉訊息機制幾個角色的建立過程,先有Looper,再有MessageQueue,最後才是Handler
  2. 熟悉執行緒中使用訊息機制的正確寫法,以及訊息的建立和傳送。
  3. 一個執行緒可以有多個Handler,這些Handler無論在哪裡傳送訊息,最終都會在建立其的執行緒中處理訊息,
    這也是能夠非同步通訊的原因。
  4. Android 提供的 AsyncTaskHandlerThread等等都用到了非同步訊息機制。

最後借用一張圖說明Android非同步訊息機制

Android非同步訊息機制
Android非同步訊息機制

四、寫在最後

至此,Android 非同步訊息機制就講解完畢了,有木有一種醍醐灌頂的感覺,哈哈~~~~,這篇文章涉及到的原始碼不難,非常好理解,關鍵還是要自己去閱讀原始碼,理解其原理,做到知其然亦知其所以然,這個道理對於大部分領域的學習都適用吧,要知道,Android發展到現在,技術越來越成熟,早已不是那個寫幾個介面就能拿高薪的時代了,市場對於Android 工程師的要求越來越高,這也提醒著我們要跟上技術發展的步伐,時刻學習,避免被淘汰。

由於水平有限,文章可能會有不少紕漏,還請讀者能夠指正,Android SDK 原始碼的廣度和深度也不是小小篇幅能夠概括的,未能盡述之處,還請多多包涵。

歡迎關注個人微信公眾號:Charming寫字的地方
CSDN:blog.csdn.net/charmingwon…
簡書:www.jianshu.com/u/05686c7c9…
掘金:juejin.im/user/59924e…
Github主頁:charmingw.github.io/

歡迎轉載~~~

相關文章