Android消息机制(三) MessageQueue源码阅读

573 阅读4分钟

什么是MessageQueue

  • 持有Looper分发的消息的列表,同时消息不能直接保存到MessageQueue中,需要通过与Looper关联的Handler对象添加。
  • 可以通过Looper.myQueue()获取当前线程的MessageQueue

MessageQueue源码解析

MessageQueue的创建

 // True if the message queue can be quit.
private final boolean mQuitAllowed;

private long mPtr; // used by native code
    
 MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
}

上述代码为MessageQueue的构造函数,其中mQuitAllowed标记当前创建的MessageQueue是否可以退出;mPtr为native层创建的MessageQueue的地址。

MessageQueue的入队(保存数据)

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;
    }
  • 当前方法传入了两个参数Message:消息体;when:执行的时间。
  • 进入方法后首先会判断当前的Message的target(也就是所属的Handler)是否为空,和当前消息是否正在使用若这两者中有为true的,则抛出异常。
  • 然后会进入同步代码块
    • 首先会通过mQuitting参数判断当前的MessageQueue是否正在退出;
    • 将Message标记为正在使用通过Message.markInUse()方法;
    • 设置Message执行时间;
    • 判断当前的Message插入的位置是否在队列头部,若是则将Message插入头部,通过mBlocked(表示当前队列是否在阻塞中)参数判断是否事件队列;
    • 若否则将Message插入到队列的中间,通过判断队列头部是否屏障且此消息是否为最早的异步消息来决定是否唤醒事件队列;
    • 通过判断消息的when参数决定当前消息插入到MessageQueue的位置
    • 方法最后会通过判断needWake参数来决定唤不唤醒事件队列。

MessageQueue的出队(取出数据)

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

                
                // 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;
        }
    }
  • 首先循环体内首先会调用nativePollOnce(ptr, nextPollTimeoutMillis)方法在native层阻塞MessageQueue ,nextpollTimeOutMillis时间;
    • nextpollTimeOutMillis=-1 时会一直阻塞;
    • nextpollTimeOutMillis=0 时会不会阻塞直接返回;
    • nextpollTimeOutMillis>0 时会阻塞nextpollTimeOutMillis时间,如果期间执行了nativeWake方法则会立即唤醒;
  • 然后判断队列头部是否为屏障消息,若是则查找下一个异步消息;
  • 再之判断消息是否为空,若不为空
    • 判断消息的执行时间是否大于当前时间,若是则将nextPollTimeoutMillis置位执行时间与当前时间的差值;
    • 若否则判断当前消息是否为异步消息;若是则将msg.next赋值给屏障消息的next
    • 若否则将mMessages值改为当前消息的next,最后返回当前消息
  • 若为空则将nextPollTimeoutMillis 置位-1表示MessageQueue中暂无消息
  • 当mMessages=null或当前时间小于mMessages.when时会执行IdleHandler(空闲消息)
  • 若空闲消息为空则会继续执行MessageQueue循环,若不为空则处理消息;
  • idle消息只会在第一次循环时执行;

总结

  • 通过上述源码了解在插入Message时会通过when(执行时间)进行排序;
  • 在取出消息时会先判断当前的时间与执行的时间大小,然后根据差值调用 nativePollOnce native方法使事件队列进行阻塞(实现延迟发送的原理)。