Android的消息機(jī)制

引言

由于Android對消息機(jī)制的封裝,開發(fā)者在平常的開發(fā)過程中,直接使用Handler對象就能滿足大部分的應(yīng)用場景,是否了解Android的消息機(jī)制對開發(fā)來說并沒有太大的影響。但Android的消息機(jī)制對開發(fā)者來說還是有很大啟發(fā)的,因為這里面有完整的異步消息處理機(jī)制以及Android的設(shè)計思路,有很大參考價值。
在最開始接觸Android的時候就了解了Android的消息機(jī)制,但在使用過程中總是選擇性的忽視一些問題:

  • Handler具體是如何實現(xiàn)跨線程通信的?
  • Handler中post的一系列方法與send的一系列方法有什么關(guān)系與不同?
  • Handler是如何與線程中的Looper進(jìn)行關(guān)聯(lián)的?
  • 在主線程不斷循環(huán)的Looper,為什么不會引起ANR?
  • Looper對象的內(nèi)部實現(xiàn)機(jī)制是怎樣?

因此,圍繞以上問題,查閱《Android開發(fā)藝術(shù)探索》及源碼,經(jīng)過學(xué)習(xí)研究之后在這里進(jìn)行總結(jié)。

Android的消息機(jī)制

Android的消息機(jī)制主要由MessageQueueLooper 、Handler三者支撐,三者的關(guān)系可以概括為:
Looper 中維護(hù)著一個MessageQueueHandler發(fā)送的消息會進(jìn)入到MessageQueue也就是消息隊列中,同時Looper會不斷的輪詢MessageQueue中是否有消息,如果存在消息,Looper將消息從MessageQueue中取出,交給Handler處理(下文會進(jìn)行具體分析)。

MessageQueue

MessageQueue中主要進(jìn)行兩個操作,消息的插入讀取,分別由enqueueMessagenext兩個方法實現(xiàn)
enqueueMessage源碼如下

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中通過鏈表的數(shù)據(jù)結(jié)構(gòu)來維護(hù)消息列表,把從外部傳遞進(jìn)來的消息(參數(shù)msg)插入到消息列表中。

next源碼如下

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

從以上代碼可以了解到next方法中啟動了一個無限循環(huán),結(jié)束該循環(huán)只有兩種情況

  • 當(dāng)消息列表中有新消息插入,next方法會返回這條消息并把這條消息從消息列表中移除
  • mQuitting為true,next方法會返回null

Looper

要了解Looper的機(jī)制可以從Looper中的兩個方法入手——prepare()loop()
首先是prepare(),用來在當(dāng)前線程中創(chuàng)建Looper

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

首先可以看到一個sThreadLocal對象,在Looper中它的定義如下

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

sThreadLocal對象是用于存放當(dāng)前線程啟動的Looper對象,從以上代碼可以了解到兩點

  • 在某線程中可以通過Looper.prepare()來創(chuàng)建Looper
  • 某線程中最多只能創(chuàng)建一個Looper,否則會拋出異常(Only one Looper may be created per thread)

然后是loop(),loop()的作用主要是啟動對MessageQueue的輪詢,一般由線程直接調(diào)用Looper.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.recycleUnchecked();
        }
    }

以上代碼中核心部分主要關(guān)注for循環(huán)中內(nèi)容,可以看到loop()方法執(zhí)行后就通過for(;;)啟動了無限循環(huán),對Looper中的MessageQueue輪詢,也就是不斷的通過MessageQueuenext方法取出消息,當(dāng)取出的消息不為空時則執(zhí)行msg.target.dispatchMessage(msg)觸發(fā)Handler處理消息;由上文對MessageQueue的介紹中可以知道,如果消息列表中沒有消息,next方法則會阻塞,因此loop()方法當(dāng)消息列表中沒有消息時是處于阻塞狀態(tài)。
那么什么時候觸發(fā)

if (msg == null) {
    // No message indicates that the message queue is quitting.
    return;
}

退出循環(huán)呢?由上文對MessageQueue的介紹中可以知道當(dāng)mQuitting為true時,next方法會返回null

if (mQuitting) {
     dispose();
     return null;
   }

這時Looper中quit的相關(guān)方法就派上用場了

public void quit() {
        mQueue.quit(false);
    }

public void quitSafely() {
        mQueue.quit(true);
    }

再看一下MessageQueue中的quit方法

void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

可以看到經(jīng)過一系列的調(diào)用,mQuitting 被賦值為true,因此在處理完所有事件,需要終止Looper的無限輪詢時,要調(diào)用Looperquit的相關(guān)方法終止loop方法中的無限循環(huán),否則Looper所在線程就會一直處于等待狀態(tài)。

Handler

為了實現(xiàn)子線程進(jìn)行IO操作,然后在主線程更新UI,避免ANR的應(yīng)用場景,通常會使用Handler實現(xiàn)跨線程通信
在主線程創(chuàng)建Handler對象并重寫handleMessage方法,在該方法中接收并處理消息,如下

Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
            }
        };

在子線程通過mHandler發(fā)送消息

mHandler.sendMessage(msg);

那么這兩段代碼背后的運行機(jī)制是怎樣的?
先從Handler的構(gòu)造方法入手,如下

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

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

可以看到我們調(diào)用的無參構(gòu)造方法Handler() 最終調(diào)用的是Handler(Callback callback, boolean async),根據(jù)Handler(Callback callback, boolean async)可以看到,Handler去獲取了當(dāng)前線程的Looper對象,通過以上代碼可以得出以下結(jié)論:

  • 創(chuàng)建Handler的線程必須維護(hù)者一個Looper對象,否則會拋出異常,所以在普通Thread中通過Handler()創(chuàng)建Handler對象前沒有調(diào)用Looper.prepare()是會導(dǎo)致異常的
  • 通過 Looper.myLooper() 獲得的Looper對象應(yīng)該是運行在創(chuàng)建Handler的線程中的,否則無法管理跨線程通信
  • 通過獲取到的Looper對象獲取該Looper對象中的消息隊列即代碼中的**mQueue **

Looper.myLooper()代碼如下

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

可以看到Looper 對象是通過sThreadLocal來獲取的,sThreadLocal中的Looper對象通過上文對Looper的介紹可以知道是在線程調(diào)用Looper.prepare()時賦值的

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中的靜態(tài)變量sThreadLocal

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

在多個線程分別都調(diào)用了Looper的prepare方法之后,是如何維護(hù)不同線程中的Looper對象的呢,也就是說Looper的myLooper方法是如何獲取到當(dāng)前線程中的Looper的 Looper對象呢?
分別看下ThreadLocal的setget方法

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

public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

抽象的看以上代碼,可以看到ThreadLocal的setget方法并不是簡單的參數(shù)賦值與獲取,而是將要存取的對象與當(dāng)前線程Thread.currentThread()產(chǎn)生關(guān)聯(lián),以實現(xiàn)在不同線程中的同一個ThreadLocal對象獲取到不同的目標(biāo)對象。
綜上所述,當(dāng)前線程有調(diào)用Looper.prepare()的情況下在調(diào)用new Handler()之后,Handler對象就能獲取到當(dāng)前線程中的Looper對象及Looper持有的MessageQueue對象
初始化之后就是發(fā)送消息了,接下來看一下Handler的消息發(fā)送機(jī)制

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

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

從以上代碼可以知道,在外部調(diào)用了sendMessage(Message msg)之后最終執(zhí)行的是enqueueMessage方法(send與post的一系列方法最終調(diào)用的都是enqueueMessage),所以我們主要關(guān)注enqueueMessage方法,在該方法中讓要發(fā)送的Message對象持有當(dāng)前Handler的引用(msg.target = this),最后將Message對象插入消息列表(queue.enqueueMessage(msg, uptimeMillis))

綜上所述,可以總結(jié)如下:

  • 1.在需要處理消息的線程中調(diào)用Looper.prepare()創(chuàng)建該線程的Looper對象,調(diào)用Looper.loop()啟動消息輪詢(主線程ActivityThread已默認(rèn)調(diào)用Looper.prepareMainLooper()與Looper.loop(),因此在Activity等在主線程運行的組件中可以直接調(diào)用new Handler()而不會拋出異常)
  • 2.通過new Handler()創(chuàng)建Handler對象,經(jīng)過一系列調(diào)用會將Handler與當(dāng)前的線程的Looper與MessageQueue進(jìn)行綁定
  • 3.Handler通過sendMessage發(fā)送消息,其實本質(zhì)上就是調(diào)用MessageQueue的enqueueMessage方法將消息對象插入消息列表中
  • 4.當(dāng)MessageQueue的消息列表中插入消息時,MessageQueue的next結(jié)束阻塞返回Message對象,Looper在loop方法的循環(huán)中獲取到Message對象,通過msg.target.dispatchMessage(msg)將消息交給Handler處理

看一下Handler的dispatchMessage

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

可以看到在dispatchMessage中優(yōu)先處理Message中的callback,這個callback其實就是在post一系列方法中傳遞過來的Runnable

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

mCallback 是一個接口,是在Handler的構(gòu)造方法中傳遞進(jìn)來的,可以看到當(dāng)mCallback 中的handleMessage方法返回值為true時Handler將不會執(zhí)行Handler中handleMessage方法。

總結(jié)

結(jié)合上文對MessageQueue 、Looper 、Handler三者的分析,再回頭看開頭提到的幾個問題

Handler具體是如何實現(xiàn)跨線程通信的?
以子線程進(jìn)行IO操作,然后在主線程更新UI,避免ANR的應(yīng)用場景為例:

  • 1.系統(tǒng)在主線程ActivityThread中已經(jīng)調(diào)用Looper.prepareMainLooper()創(chuàng)建主線程的Looper,并調(diào)用Looper.loop(),啟動輪詢,不斷地通過MessageQueue的next方法從消息列表中取出消息,當(dāng)沒有消息是,next處于阻塞狀態(tài),Looper.loop()也處于阻塞狀態(tài)
  • 2.當(dāng)我們在Activity等運行在主線程的組件中創(chuàng)建Handler時,Handler通過Looper.myLooper()獲取與當(dāng)前線程也就是主線程關(guān)聯(lián)的Looper對象,同時Handler也持有了Looper中的MessageQueue
  • 3.子線程持有主線程創(chuàng)建的Handler對象,在子線程中通過Handler的send或post的系列方法發(fā)送消息,send與post的系列方法最終都是通過Handler持有的MessageQueue對象調(diào)用enqueueMessage方法將消息插入隊列,觸發(fā)在主線程主線程中輪詢的Looper用過loop()取出消息,并在loop()中調(diào)用Handler的dispatchMessage方法,將消息交由Handler處理,最終達(dá)到了子線程進(jìn)行IO操作后發(fā)送消息,主線程處理消息并刷新UI的目的

Handler中post的一系列方法與send的一系列方法有什么關(guān)系與不同?

  • 從上文對Handler的介紹中可以知道,Handler中post的一系列方法與send的一系列方法本質(zhì)上最終都是通過MessageQueue對象調(diào)用enqueueMessage進(jìn)行消息插入操作,只是在調(diào)用優(yōu)先級上存在一點差別,具體從Handler的dispatchMessage方法可以看出
public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

Handler是如何與線程中的Looper進(jìn)行關(guān)聯(lián)的?
通過上文可以知道,Looper是在線程中通過Looper.preare()(主線程為preareMainLooper)創(chuàng)建的,preare的內(nèi)部通過ThreadLocal將Looper保存并與當(dāng)前線程相關(guān)聯(lián),Handler中通過Looper.myLooper獲取到Looper,myLooper的內(nèi)部則也是通過ThreadLocal來獲取Looper,從而完成了Handler與當(dāng)前線程中的Looper的關(guān)聯(lián)

Looper對象的內(nèi)部實現(xiàn)機(jī)制是怎樣?
具體參考上文對Looper的分析,這里就不重復(fù)展開

那么還有一個問題
在主線程不斷循環(huán)的Looper,為什么不會引起ANR?

主線程中的Looper.loop()一直無限循環(huán)為什么不會造成ANR?http://www.itdecent.cn/p/cfe50b8b0a41
這篇文章已經(jīng)回答了這個問題

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

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

  • 1. ANR異常 Application No Response:應(yīng)用程序無響應(yīng)。在主線程中,是不允許執(zhí)行耗時的操...
    JackChen1024閱讀 1,593評論 0 3
  • 前言 Handler是Android消息機(jī)制的上層接口,平時使用起來很方便,我們可以通過它把一個任務(wù)切換到Hand...
    eagleRock閱讀 1,745評論 0 13
  • Android平臺上,主要用到的通信機(jī)制有兩種:Handler和Binder,前者用于進(jìn)程內(nèi)部的通信,后者主要用于...
    帝都De霧霾閱讀 1,553評論 1 7
  • 上帝啊,我下個賭注,賭人生的軌跡是可以通過自我奮斗改變的。 終于,我懷疑匆忙了,它似乎能讓人一無所有,就像打地鼠,...
    若優(yōu)閱讀 276評論 0 1
  • 隨著《爸爸去哪兒》開播,一大波萌娃撲面而來讓人忍不住姨母心泛濫啊,美滋滋~~~ 嗯哼、Jasper、Neinei、...
    青囪閱讀 636評論 0 1

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