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

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

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

1、寫在前面

爲何要學習Android異步消息機制?和AMS、WMS、View體系同樣,異步消息機制是Android framework層很是重要的知識點,掌握了對於平常開發、問題定位和解決都是很是有幫助的,會使的咱們開發事半功倍。而要想成爲一個合格的Android開發人員,光是懂得調用Android提供的那些個api是不夠的,還要學會分析這些api背後的原理,知道它們是若是工做的,作到知其然亦知其因此然,若是不去學習技術背後的原理,只流於表面,這樣永遠都不會有進步,永遠都只是一個Android菜鳥。git

2、源碼分析

一、主線程建立Looper

Android中主線程也就是咱們所說的UI線程,能夠簡單理解爲全部的界面呈現,能看獲得的操做,全部的觸摸、點擊屏幕、更新界面UI事件的處理,都是在主線程中完成的。一個線程只有一條執行路徑,若是主線程同時有多個事件要處理,那麼是怎麼作到有條不紊地處理的呢?接下來,以上提到的幾個角色就要登場了,就是Handler+Looper+MessageQueue這三個角色在起做用。github

Looper是線程的消息輪詢器,是整個消息機制的核心,來看看主線程的Looper是如何建立的。api

主線程開啓於 ActivityThreadmain 方法中,來看一下 main 方法的源碼。bash

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只能被建立一次,不然會拋異常,以上源碼能夠很好地解釋。app

二、子線程建立Looper

與主線程稍稍有點不同,子線程的Looper須要手動去建立,而且有些地方是須要注意的,下面讓咱們一塊兒來探究一下。less

子線程建立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

三、MessageQueue的建立

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

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

可見在每一個線程建立Looper的時候也建立了一個MessageQueue,並將MessageQueue對象做爲該線程Looper的成員變量,這就是MessageQueue的建立過程。

四、開啓消息輪詢

有了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是怎麼建立併發送消息的

五、建立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;
            }
        });複製代碼

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

六、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; }複製代碼

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

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

七、消息的處理

回到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()

3、總結

  1. 熟悉消息機制幾個角色的建立過程,先有Looper,再有MessageQueue,最後纔是Handler
  2. 熟悉線程中使用消息機制的正確寫法,以及消息的建立和發送。
  3. 一個線程能夠有多個Handler,這些Handler不管在哪裏發送消息,最終都會在建立其的線程中處理消息,
    這也是可以異步通訊的緣由。
  4. Android 提供的 AsyncTaskHandlerThread等等都用到了異步消息機制。

最後借用一張圖說明Android異步消息機制

Android異步消息機制
Android異步消息機制

4、寫在最後

至此,Android 異步消息機制就講解完畢了,有木有一種醍醐灌頂的感受,哈哈~~~~,這篇文章涉及到的源碼不難,很是好理解,關鍵仍是要本身去閱讀源碼,理解其原理,作到知其然亦知其因此然,這個道理對於大部分領域的學習都適用吧,要知道,Android發展到如今,技術愈來愈成熟,早已不是那個寫幾個界面就能拿高薪的時代了,市場對於Android 工程師的要求愈來愈高,這也提醒着咱們要跟上技術發展的步伐,時刻學習,避免被淘汰。

因爲水平有限,文章可能會有很多紕漏,還請讀者可以指正,Android SDK 源碼的廣度和深度也不是小小篇幅可以歸納的,未能盡述之處,還請多多包涵。

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

歡迎轉載~~~

相關文章
相關標籤/搜索