Android 实战中提高Handler发送消息的优先级

在阅读分析Android 绘制原理的源码时,挺多文章指出绘制消息message的执行肯定优先所有的同步message(这句话有待商榷,暂时这么说),这个优先机制是利用Handler的同步屏障机制和异步消息,但是这些机制对开发者不开放的,相关方法也标注为@hide,我猜测如果对开发者开放,那么开发者可能为了使得自己业务的消息优先执行而采用同步屏障和异步消息,结果绘制的消息不能优先执行,恰好业务消息执行比较耗时,vsync信号到达后不能马上执行,则会导致卡顿.分析同步屏障和异步消息的原理文章已经很多,大牛们分析的肯定比我透彻很多,哈哈.

但是实战中,会有优先执行的需求,尤其在开屏处理逻辑的时候.虽然绘制这一类有同步屏障机制的异步消息能优先执行.但在之后的同步消息中我们是否可以让自己的消息优先执行呢,查阅Handler的源码中,有如下几个方法可以实现这样的效果

Handler 类:


    public final boolean postAtFrontOfQueue(@NonNull Runnable r) {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }


    public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg) {
        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, 0); 
    }

    private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

 二其余发送消息的API 无论是post,sendMessage等,最终也会调用enqueueMessage(),不过区别就在enqueueMessage()方法中的第三个参数uptimeMillis,postAtFrontOfQueue最终调用sendMessageAtFrontOfQueue,所以只要看sendMessageAtFrontOfQueue调用enqueueMessage方法,传入uptimeMillis是0,而其余的要么是系统当前时间,要么系统当前时间加延迟的时间.

Handler 类

  public final boolean sendMessage(@NonNull Message msg) {
        return sendMessageDelayed(msg, 0);
    }

   public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
// uptimeMillis是系统时间或者系统时间加上延迟的时间
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    public boolean sendMessageAtTime(@NonNull 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);
    }

看下MessageQueue的enqueueMessage方法传0和不传0的区别

MessageQueue类

    boolean enqueueMessage(Message msg, long when) {

        //when 接收了uptimeMillis的值
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            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.
                //当when == 0的时候,是走这个逻辑的,相当于msg作为新的链表的头结点
                //这里还有一个when<p.when的条件,什么时候触发,后面在分析 
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //else的执行中逻辑当正常post,sendMessage的时候,when接收的时间值是大于等于系统 
                //  时间,肯定也比头结点所在的时间要大
                // 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;
    }

分析得到,如果uptimeMillis是0的话,那么会让当前的消息成为头结点.如图所示

所以这个消息除了采用同步屏障的异步消息外,肯定优先执行.理论上是这样,实操中是如此吗?因为demo过于简单,只贴出核心方法.

 fun  postDemos(){
        //1 post
        handler.post {
            Log.i(TAG,"1 post")
        }
        //2 send message
        val msg = Message.obtain()
        msg.what = 1
        msg.obj = "2 send message"
        handler.sendMessage(msg)
        //3 post
        handler.post {
            Log.i(TAG,"3 post")
        }
        //4 post
        handler.post {
            Log.i(TAG,"4 post")
        }
        //5 send message
        val msg1 = Message.obtain()
        msg1.what = 1
        msg1.obj = "5 send message"
        handler.sendMessage(msg1)

        //6 postFirset
        handler.postAtFrontOfQueue {
            Log.i(TAG,"6 postFirst")
        }

        //7 sendMessageAtTime
        val msg2 = Message.obtain()
        msg2.what = 1
        msg2.obj = "7 send message"
        handler.sendMessageAtFrontOfQueue(msg2)
    }

这个方法输出的日志是这样的 

2021-09-19 08:48:45.251 6532-6532/com.hy.learndemo I/MainActivity: 7 send message
2021-09-19 08:48:45.251 6532-6532/com.hy.learndemo I/MainActivity: 6 postFirst
2021-09-19 08:48:45.252 6532-6532/com.hy.learndemo I/MainActivity: 1 post
2021-09-19 08:48:45.252 6532-6532/com.hy.learndemo I/MainActivity: 2 send message
2021-09-19 08:48:45.252 6532-6532/com.hy.learndemo I/MainActivity: 3 post
2021-09-19 08:48:45.252 6532-6532/com.hy.learndemo I/MainActivity: 4 post
2021-09-19 08:48:45.252 6532-6532/com.hy.learndemo I/MainActivity: 5 send message

很明显,postAtFrontOfQueue,sendMessageAtFrontOfQueue发送的消息虽然在最后入队列,但优先执行,不过7比6先执行是怎么回事,那是因为sendMessageAtFrontOfQueue后执行,所以最后的头结点就是它发送的消息.在分析enqueueMessage方法执行逻辑的时候,这里留一个问题。什么时候会触发when<p.when.除了0之外,也就是说存在一种情况需要发送的消息的时间值还能比头结点的时间还小,还记得sendMessageAtTime这个方法吗,这个方法是public方法,没有标注为@hide,所以我们也能用,重新贴一下方法

    public boolean sendMessageAtTime(@NonNull 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);
    }

传入的 uptimeMillis并没有做小于当前时间的校验,是支持传入小于当前时间的消息.所以优先执行消息除了刚才说的postAtFrontOfQueue,sendMessageAtFrontOfQueue之外,还有一个方法就是调用sendMessageAtTime,传入比当前时间小的时间戳.不过不建议直接调用sendMessageAt()方法,最好调用现成的postAtFrontOfQueue或者sendMessageAtFrontOfQueue.相反在sendMessageAtTime方法中,如果传入比当前时间值大,效果就是在某个指定的时间点执行消息.所以Handler机制对消息执行的优先级以及时间自由度还是挺大的.

继续分析下去,发现有个点很有意思,就是说插入同步屏障之后,同步屏障消息成为头结点,在等异步消息入队之前。但恰好中间一个时间点调用postAtFrontOfQueue,直接把头结点换了,那是不是同步屏障消息失效了?优先执行了新头结点的同步消息,这比同步屏障还牛逼.我想在Hanlder机制中应该在发送同步消息的各个方法前面是不是加入一个逻辑,遇到头结点是同步屏障的话,不能替换头结点,即使postAtFrontOfQueue,插入的消息顺序应该在同步屏障后面,而不是直接更新头结点,我觉得Android 团队应该考虑了这一点,没加入这个判断逻辑可能是另外一个方面考虑,我猜不到,如果有朋友知道其中的原有,感谢在评论区留言解答我的困惑

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值