桥下红药

机器应该工作、人类应该思考

Handler postDelayed 的实现

Android, 全部 评论已关闭

都知道 Handler 的工作原理,也清楚 Handler 、Looper 、MessageQueue 三个基佬之间的一些 py 交易,自然的 postDelayed 延迟处理也离不开这些。

1. 记录开始

public final boolean postDelayed(Runnable r, long delayMillis){
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis){
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
  • 调用getPostMessage方法把Runnable封装成Message对象。
  • 最后调用sendMessageAtTime把时间转换成绝对时间,放入 MessageQueue 中,也就是 mQueue 变量。

2. 再切换到Looper的视角

  • Looper 的工作逻辑在 loop() 方法内,代码判断比较多,看见第一行就是 myLooper() ,刚好涉及到一个问题,如何保证一个线程只有一个Looper对象,答案就在这个方法里面,ThreadLocal 类。

  • loop() 主要是 通过 next()获取队列消息,获取到以后执行 msg.target.dispatchMessage(msg); 就运行了我们设置的Runnable回调。

    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;
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // 获取队列消息,可能阻塞
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            try {
                // 执行 Runnable 回调
                msg.target.dispatchMessage(msg);
            } finally {
            }
            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            msg.recycleUnchecked();
        }
    }

3. next() 取队列消息

大致的思路是这样的~

  • 如果获取消息发现是个 延迟消息,就会阻塞 next()方法,直到时间到了被唤醒继续执行,再一次轮询 next()方法。
  • 如果获取的不是延迟消息,那么一系列的逻辑最后返回就可以了。

那么问题是如果是个延迟消息代码被阻塞了,后面继续添加非延迟消息怎么办?

    Message next() {
        // 空闲的Handler数量
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                // 说明后面的代码可能会引起线程阻塞
                Binder.flushPendingCommands();
            }
            // 通过nextPollTimeoutMillis剩余时间,调用系统层 epoll 延时唤醒,会阻塞
            // 猜测 nextPollTimeoutMillis = 0 的话可能不会有效果,因为不是延迟消息或已经到时间的延迟消息,就可以直接返回消息了。
            nativePollOnce(ptr, nextPollTimeoutMillis);
            // 遍历mMessages链表获取Message
            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.
                // 当这个消息队列退出的时候,返回空。而且在返回前调用了dispose()方法,显然这意味着该消息队列将被释放。
                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;
        }
    }

接着上面的问题,队列前面的延迟消息阻塞了Looper,next() 进入了休眠。再次添加一个非延迟消息。 代码就在 MessageQueueenqueueMessage方法。

msg.when = when;
//这是一个根据when排序的链表,when最短的排在最前面
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
    // New head, wake up the event queue if blocked
    // 发现新插入的消息不是延迟消息,或者比mMessages里面的when还要小那么就插入到mMessages最前面,然后可能是等待Looper再次轮询,或者需要唤醒阻塞的线程
    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.
    //这里就是遍历mMessages把新添加的Message根据when插入到一个合适的位置(调整next的指向)
    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);
}

基本就了解了,Looper 获取到 延迟消息后会判断多久之后执行,如果没到时间就是阻塞(休眠)线程,这个时候如果 MessageQueue 添加进一个 非延迟消息,会在添加进队列的时候进行排序插入到最前面,然后唤醒线程,这个线程执行后续代码遍历拿到刚刚添加最上面的非延迟消息执行...

上一篇

评论已关闭。