欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

源码分析:Handler发送延时消息

程序员文章站 2022-07-14 16:46:34
...

前言

Handler的消息分发机制相信都已经知道了,那么Handler发送延时消息是怎么实现的呢?
解答这个问题前先提出两个问题,然后围绕两个问题进行源码分析

1.Handler发送延时消息的方式

2.message在MessageQueue中是怎么存储的呢?

Handler发送延时消息的方式

源码基于Android API 28

public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
    
/*
token是一个实例,可以用来在removeCallbacksAndMessages中取消某个消息
*/
public final boolean postDelayed(Runnable r, Object token, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r, token), delayMillis);
    }

可以看到这两个方法是将Runnable对象封装成Message,然后调用了sendMessageDelayed()

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

最终都是调到了sendMessageAtTime(),在这个方法中调用了handler#enqueueMessage()方法插入一条msg到队列中,真正的入队列操作是MessageQueue#enqueueMessage()

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

总结:
handler发送延时消息是通过postDelayed()方法将Runnanle对象封装成Message,然后调用sendMessageAtTime(),设置的时间是当时的时间+延时的时间。发送延时消息实际上是往messageQueue中加入一条Message。

message在MessageQueue中是怎么存储的呢?

这就需要看MessageQueue#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;
    }

总结:
Message在MessageQueue中实际是以单链表来存储的,且是按照时间顺序来插入的。时间顺序是以Message中的when属性来排序的。

相关标签: Android android