深入理解Handler、Looper與MessageQueue之間的關(guān)系

如果想要弄懂Android的消息機(jī)制,就一定要深入挖掘HandlerMessageQueueLooper這三者之間的關(guān)系。

關(guān)系圖.png

1.開啟消息循環(huán)

從一個普通的子線程開啟Looper循環(huán)講起:

new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Handler handler = new Handler();
                Looper.loop();
            }
        }).start();

上面的代碼我們分三步來研究:
①Looper.prepare()
②new Handler()
③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);
        mThread = Thread.currentThread();
    }

可以看到,Looper.prepare()最終調(diào)用的是自身的構(gòu)造函數(shù),在構(gòu)造函數(shù)中實(shí)例化了一個MessageQueue,并獲取了當(dāng)前的線程。通過將實(shí)例化的Looper放在ThreadLocal中,從而實(shí)現(xiàn)Looper和線程的綁定。

下面看看new MessageQueue(quitAllowed)做了些什么

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

MessageQueue在構(gòu)造函數(shù)中通過native方法進(jìn)行了初始化工作。

②new Handler():

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

Handler在構(gòu)造函數(shù)中通過Looper.myLooper()來獲取在當(dāng)前線程中創(chuàng)建的Looper對象(所以在子線程中需要手動寫Looper.prepare(),否則mLooper為null會報(bào)異常。由于主線程會自動創(chuàng)建smainLooper,所以在主線程中實(shí)例化的Handler無需手動創(chuàng)建Looper也不會報(bào)異常。關(guān)于主線程的消息機(jī)制最后會講到)。此外,還獲取了mLooper中的messageQueue對象,并將異步狀態(tài)設(shè)為false。

③Looper.loop():

關(guān)鍵的地方來了

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

我們可以清晰地看到,loop方法實(shí)際是執(zhí)行的一個死循環(huán)。
在該循環(huán)中,MessageQueue通過調(diào)用next()來獲取Message。
如果msg==null,則跳出該循環(huán)(也意味著此消息隊(duì)列結(jié)束);如果msg不為空,則會執(zhí)行msg.target.dispatchMessage(msg)。這里的target是發(fā)送Message時對應(yīng)的Handler(后面會講到為什么),所以這一句代碼的功能本質(zhì)上是調(diào)用handler.dispatchMessage(msg),也就是將從MessageQueue中讀到的Message通過Handler作分發(fā)操作。

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

而dispatchMessage就比較容易理解了,通過判斷有無callback來選擇具體的執(zhí)行方法。在這里就可以看到我們平時繼承Handler最常復(fù)寫的方法--handleMessage(msg)。

剛才談到了Looper.loop()的死循環(huán)中會通過MessageQueue的next()方法來獲取Message,那么我們再深入去看看這個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;
        }
    }

可以發(fā)現(xiàn),next()也是個無限循環(huán)的方法,如果消息隊(duì)列中沒有消息,則會一直阻塞在這里。只有當(dāng)msg != nullnow >= msg.when時才會return msg。其中now表示當(dāng)前時間,msg.when表示插入該msg時所指定的期望處理該任務(wù)的時間。如果now < msg.when,表示當(dāng)前消息還未到執(zhí)行它的時間,那么就會計(jì)算時間差并進(jìn)行休眠以等待執(zhí)行時間到來。
此外,mQuitting==true,則會return null,表示關(guān)閉該消息隊(duì)列。

到這里,我們基本上看完了在子線程中開啟消息循環(huán)的大致流程。系統(tǒng)所做的無非就是實(shí)例化一個Looper并將它與當(dāng)前線程綁定,然后將Handler的實(shí)例化對象與Looper進(jìn)行綁定,再在Looper中無限循環(huán)地調(diào)用MessageQueue的next()方法來循環(huán)的讀取Message。如果讀到了Message,則會調(diào)用該Message所綁定的Handler對象來執(zhí)行對應(yīng)的分發(fā)和處理操作。

2.發(fā)送消息

發(fā)送消息抽象的解釋就是通過Handler將Message放入MessageQueue中。對于發(fā)送消息這個操作,Android SDK為我們提供了多種Message構(gòu)造以及Handler發(fā)送的方式。

Message有兩種常用的構(gòu)造方式:new Message()handler.obtainMessage()。下面貼上源碼來比較二者差別。

以下為Handler.java的部分源碼
    public final Message obtainMessage()
    {
        return Message.obtain(this);
    }

    public final Message obtainMessage(int what)
    {
        return Message.obtain(this, what);
    }

    public final Message obtainMessage(int what, Object obj)
    {
        return Message.obtain(this, what, obj);
    }

    public final Message obtainMessage(int what, int arg1, int arg2)
    {
        return Message.obtain(this, what, arg1, arg2);
    }

    public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
    {
        return Message.obtain(this, what, arg1, arg2, obj);
    }

可以看到handler的obtainMessage方法的多個重載主要區(qū)別在于給Message添加的參數(shù)上的不同,其內(nèi)部實(shí)現(xiàn)還是得進(jìn)入Message源碼中去查看。

    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;

    /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
    */
    public Message() {
    }

    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

    public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;

        return m;
    }

    public static Message obtain(Handler h, int what, Object obj) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.obj = obj;

        return m;
    }

    public static Message obtain(Handler h, int what, int arg1, int arg2) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.arg1 = arg1;
        m.arg2 = arg2;

        return m;
    }

    public static Message obtain(Handler h, int what,
            int arg1, int arg2, Object obj) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.arg1 = arg1;
        m.arg2 = arg2;
        m.obj = obj;

        return m;
    }

可以看到,Message的obtain方法的多個重載,本質(zhì)上還是通過無參的obtain方法獲取Message對象,然后把傳入的參數(shù)設(shè)入其中。
仔細(xì)查閱無參obtain方法的實(shí)現(xiàn),我們可以發(fā)現(xiàn)這就是簡單的單鏈表取鏈表頭元素的操作。其首先進(jìn)行了線程同步,即當(dāng)前只有一個線程可以執(zhí)行此方法。然后取出sPool這個鏈表頭所指向的Message對象,并將sPool指向鏈表的下一結(jié)點(diǎn),鏈表長度計(jì)數(shù)減一,然后返回剛剛?cè)〕龅腗essage對象。只有當(dāng)前sPool即鏈表頭為null時才執(zhí)行new Message()方法來構(gòu)造Message對象。

那么問題來了,既然Message是以鏈表的形式存取的,那也應(yīng)該在某處對應(yīng)著插入鏈表的操作才對。仔細(xì)想想一個Message會在什么時候回收并插入鏈表中呢?一定是在Message被處理完之后。那么我們再回過頭去看看Looper的loop方法。

    public static void loop() {
       
        省略部分代碼
        for (;;) {

            !!從MessageQueue中取Message!!
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            省略部分代碼
            try {
                !!調(diào)用Handler處理Message!!
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } 
            省略部分代碼
            !!回收Message!!
            msg.recycleUnchecked();
        }
    }

可以看到,通過msg.target.dispatchMessage(msg)完成了對Message的處理,隨后便調(diào)用了msg.recycleUnchecked()來對Message進(jìn)行回收操作。

  void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

不難看出,回收操作中先是清除Message中各類參數(shù)的信息,隨后依然是通過sPoolSync這個鎖進(jìn)行線程同步,最后便是將當(dāng)前Message對象的next指向鏈表頭sPool,再將sPool指向當(dāng)前對象,最后鏈表長度計(jì)數(shù)加一,即完成了一次單鏈表頭插的操作。

小總結(jié)

正如Message構(gòu)造函數(shù)上所提到的,更傾向于通過obtain方法來獲取一個Message對象而不是主動去實(shí)例化一個Message對象。因?yàn)锳ndroid程序是基于事件驅(qū)動的,事件的發(fā)送是一個高頻操作。無論是系統(tǒng)的消息,還是自己發(fā)送的消息,如果每次都實(shí)例化一個新的Message對象,這無疑會對內(nèi)存會構(gòu)成較大的壓力。所以Message才會采用單鏈表的形式在每次使用完之后進(jìn)行回收,并在使用時從鏈表中取出來進(jìn)行復(fù)用。


下面我們再看看Handler是如何發(fā)送Message的。
Handler發(fā)送Message主要有兩種方式:sendMessage(Message msg)h和post(Runnable r)。

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

    public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }

    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }

    public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
    
    //將Runnable轉(zhuǎn)化成Message
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

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

從上面代碼中我們能看到post(Runnable r)實(shí)際上是將Runnable設(shè)置給了Message的callback變量,然后走的還是sendMessage方法。

而sendMessage相關(guān)的一系列操作,主要是通過延遲時長delayMillis和系統(tǒng)當(dāng)前時間來計(jì)算該Message的預(yù)計(jì)處理時間uptimeMillis

隨后,在enqueueMessage方法中,我們可以看到msg.target = this;這樣一行代碼,這也印證了我們上面提到的Message中的target指的其實(shí)就是發(fā)送它的Handler。再通過queue.enqueueMessage(msg, uptimeMillis)方法,將Message插入到MessageQueue中。

接下來我們再看看MessageQueue具體是如何將Message放進(jìn)消息隊(duì)列中的。

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

兩個關(guān)鍵位置:
if (p == null || when == 0 || when < p.when)
與這個if判斷相關(guān)的三個條件分別是消息隊(duì)列的頭節(jié)點(diǎn)是否為null;傳入的參數(shù)when是否為0;傳入的參數(shù)when是否小于當(dāng)前消息隊(duì)列頭節(jié)點(diǎn)對應(yīng)的when。三者滿足其一就可將傳入的msg插入到消息隊(duì)列的頭節(jié)點(diǎn)處。
for (;;)
這個for循環(huán)當(dāng)中執(zhí)行的遍歷鏈表的操作,當(dāng)遍歷到末尾或者when < p.when時,便將msg插入到此位置。

看到這兒也順帶解釋了一個問題:Message插入MessageQueue是順序插入的還是基于某些原則插入的?
答:通過比較msg的參數(shù)when的大小來插入到MessageQueue的對應(yīng)位置。

至此,Handler、MessageQueue、Looper三者的關(guān)系我們就全部梳理了一遍。


PS:主線程的消息循環(huán)

Android的主線程是ActivityThread,其通過在入口main()方法中調(diào)用下面幾行代碼來實(shí)現(xiàn)的消息循環(huán):

//省略部分代碼
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
}
//省略部分代碼
Looper.loop();
//省略部分代碼

與子線程相比,區(qū)別主要體現(xiàn)在prepareMainLooper和prepare,以及Handler的生產(chǎn)方式不同上。

那么prepareMainLooper有何特殊呢?
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

可以看到,prepareMainLooper其實(shí)也是調(diào)用的prepare方法,只不過參數(shù)為false,表示該線程不允許退出。

主線程上的Handler又有何區(qū)別呢?

ActivityThread內(nèi)部的handler中定義了一組消息類型,主要包含了四大組件的啟動和停止等過程。handler接收到消息后會將邏輯切換到主線程去執(zhí)行,這也就是主線程的消息循環(huán)模型。

public void handleMessage(Message msg) {
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
        switch (msg.what) {
            case LAUNCH_ACTIVITY: {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
                handleLaunchActivity(r, null);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
            break;
            case RELAUNCH_ACTIVITY: {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
                ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                handleRelaunchActivity(r);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
            break;
            case PAUSE_ACTIVITY:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                handlePauseActivity((IBinder) msg.obj, false, (msg.arg1 & 1) != 0, msg.arg2, (msg.arg1 & 2) != 0);
                maybeSnapshot();
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
            case PAUSE_ACTIVITY_FINISHING:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                handlePauseActivity((IBinder) msg.obj, true, (msg.arg1 & 1) != 0, msg.arg2, (msg.arg1 & 1) != 0);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
            ...........
        }
    }
主線程上Looper一直無限循環(huán)為什么不會造成ANR?

首先我們要明白造成ANR的原因:
①當(dāng)前的事件沒有機(jī)會得到處理(即主線程正在處理前一個事件,沒有及時的完成或者looper被某種原因阻塞住了)
②當(dāng)前的事件正在處理,但沒有及時完成

Android系統(tǒng)是由事件驅(qū)動的,Looper的作用就是在不斷的接收事件、處理事件,如Activity的生命周期或是點(diǎn)擊事件。Looper的無限循環(huán)正是保證了應(yīng)用能持續(xù)運(yùn)行。如果Looper循環(huán)結(jié)束,也代表著應(yīng)用停止。

再回到這個問題,我們可以發(fā)現(xiàn),ANR正是由Looper中那些耗時的事件所造成的,從而導(dǎo)致Looper的消息循環(huán)無法正常進(jìn)行下去。

主線程的死循環(huán)一直運(yùn)行是不是特別消耗CPU資源呢?
其實(shí)不然,這里就涉及到Linux pipe/epoll機(jī)制,簡單說就是在主線程的MessageQueue沒有消息時,便阻塞在loop的queue.next()中的nativePollOnce()方法里,詳情見Android消息機(jī)制1-Handler(Java層),此時主線程會釋放CPU資源進(jìn)入休眠狀態(tài),直到下個消息到達(dá)或者有事務(wù)發(fā)生,通過往pipe管道寫端寫入數(shù)據(jù)來喚醒主線程工作。這里采用的epoll機(jī)制,是一種IO多路復(fù)用機(jī)制,可以同時監(jiān)控多個描述符,當(dāng)某個描述符就緒(讀或?qū)懢途w),則立刻通知相應(yīng)程序進(jìn)行讀或?qū)懖僮?,本質(zhì)同步I/O,即讀寫是阻塞的。 所以說,主線程大多數(shù)時候都是處于休眠狀態(tài),并不會消耗大量CPU資源。


參考文獻(xiàn):

《Android開發(fā)藝術(shù)探索》
《深入理解Android內(nèi)核設(shè)計(jì)思想》
https://www.zhihu.com/question/34652589



若您覺得本文章對您有用,請您為我點(diǎn)上一顆小心心以表支持。感謝!

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

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

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