天天看點

10分鐘掌握Android消息機制(三)MessageQueue

本文為個人學習筆記分享,沒有任何商業化行為,對其他文章的引用都會标記。如有侵權行為,請及時提醒更正!如需轉載請表明出處

本文主要來源是 任玉剛大神的《Android開發藝術探索》

10分鐘掌握Android消息機制(三)MessageQueue

消息隊列在Android中指的是MessageQueue,MessageQueue主要包含兩個操作:插入和讀取。讀取操作本身伴随着删除操作。插入和讀取對于的方法分别為enqueueMessage和next,其中enqueueMessage的作用是往消息隊列中插入一條消息,而next的作用是從消息隊列中取出一條消息并将其從消息隊列中移除。盡管MessageQueue叫消息隊列,但是它的内部實作并不是用的隊列,實際上它是通過一個單連結清單的資料結構來維護消息清單,單連結清單插入和删除上比較有優勢。下面主要看一下enqueueMessage和next的方法實作,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來看,它的主要操作其實就是單連結清單的插入,這裡就不過多解釋了,下面看一下next方法的實作,next的主要邏輯如下所示。

Message next() {
        ...
        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;
                }
                ...
           }
        ....
    }

           

可以發現next方法是一個無線循環的方法,如果消息隊列中沒有消息,那麼next方法會一直阻塞在這裡。當有新消息到來時,next方法會傳回這條消息并将其從單連結清單移除。

整理寫作不易,請小夥伴多多支援,麻煩請點贊關注支援一下,???。