Android異步消息機制-深入理解Handler、Looper和MessageQueue之間的關系

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:http://blog.csdn.net/charmingwong
簡書:http://www.lxweimin.com/u/05686c7c92af
掘金:https://juejin.im/user/59924ed5f265da3e161aa74e
Github主頁:https://charmingw.github.io/

歡迎轉載~~~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容