Handler消息屏障

一.Handler消息添加在MessageQueue中,消息的排序顺序

先来从它的发送消息方法跟踪:

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

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

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

发送消息从sendEmptyMreeageDelayed到sendMessageDelayed,最后到sendMessageAtTime()方法,把消息传进去之外,还传了消息时间(系统启动时间+用户定义的时长),这个消息时间特别重要。

接下来我们知道会走到MessageQueue的enqueueMessage方法里面:

boolean enqueueMessage(Message msg, long when) {
    ...
            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 {
                ...
            }
...

这段代码其实很好理解,第一条消息进来时,P对象为空,mMessages对象也是为空,然后此时p==null成立,因此走if里面的代码块,然后让当前这条要发送的消息的下一个消息对象next引用指向p(也就是null),然后让mMessages等于当前消息对象。

当第二条消息进来时,又重新new了一个p对象,让它等于mMessage(也就是第一条消息对象),p对象也就是上一个message对象了。这次进来就需要判断第二条消息的时间是不是小于第一条消息的时间,也就是when < p.when是否成立,如果是小于的情况,那么就让当前消息对象msg(也就是第二条消息)的下一个指向next引用指向p(也就是第一条消息对象),接着让mMessages对象等于第二条消息对象。那现在这种情况也就是说如果我发送的第二条消息对象的时间是比第一条消息对象的时间还要小的 话,那么就会让第二条消息排在第一条消息对象的前面,也就是先让第二条消息先发送:

第三条消息的时间也是比第二条消息要小,所以依然第三条消息的next引用指向第二条消息对象,那么当第四条消息对象的时间是比第三条消息对象的时间要大的话,则就走else块的代码,来看看会发生什么:

boolean enqueueMessage(Message msg, long when) {
    ...
            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;
            }

我们可以看到,先创建一个message对象prev,让prev等于p(p等于mMessages),也就是prev等于这个链表的表头消息,p等于p.next,p就是表头消息的下一个消息。不断地去循环,直到当前要插入的message的时间小于p的时间时候,或者已经到队列尾部的时候,再把当前链表断开,插入当前的message。

所以,handler的消息排序机制也就是靠这个时间when来决定谁先谁后,小的那个排在大的后面,借由单链表的插入特性来进行插入。

二.消息屏障

handler的消息分为三种:同步消息,异步消息,屏障消息。

屏障消息

android里面屏幕刷新的优先级是最高的。

我们都知道消息的执行是沿着消息队列里面消息的顺序取执行的。如果现在消息队列里面有很多消息还没执行,这时候屏幕刷新的消息又添加到消息队列里面了,就需要先执行屏幕刷新的消息,确保屏幕刷新正常。

这时候就需要消息屏障了。

消息屏障是怎么创建的:

 private int postSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;

            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }

在MessageQueue里面调用postSyncBarrier就可以创建一个消息屏障,我们可以看到这个消息与正常的消息的区别在于,屏障消息没有持有handler,traget为null。这边我们还是可以看到屏障消息存在消息队列里面是根据时间顺序来存储的。

所以我们可以说屏障消息就是traget为null的消息。

异步消息

异步消息在ViewRootImpl里面:


    @UnsupportedAppUsage
    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier()先发屏障消息,后通过

mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);发了一个异步消息。

mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null)最后调用的是:

 private void postCallbackDelayedInternal(int callbackType,
            Object action, Object token, long delayMillis) {
        if (DEBUG_FRAMES) {
            Log.d(TAG, "PostCallback: type=" + callbackType
                    + ", action=" + action + ", token=" + token
                    + ", delayMillis=" + delayMillis);
        }

        synchronized (mLock) {
            final long now = SystemClock.uptimeMillis();
            final long dueTime = now + delayMillis;
            mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token);

            if (dueTime <= now) {
                scheduleFrameLocked(now);
            } else {
                Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);
                msg.arg1 = callbackType;
                msg.setAsynchronous(true);
                mHandler.sendMessageAtTime(msg, dueTime);
            }
        }
    }

可以看到异步消息是msg.setAsynchronous(true)标识的。

三种消息在消息队列里面的排序

发送异步消息的时候必会先发送一个屏障消息,这些消息在消息队列里面的排序是根据时间来的。

我们都知道处理消息的时候,每次都是从消息队列头取消息的。如果在onResume的时候,handler的消息处理太耗时,通常会报错“Skipped 30 frames! The application may be doing too much work on its main thread.”这句话的意思就是说在执行完handler消息的时候,当发现存在屏障消息的时候,队列里面已经有30个异步消息了。

所有子线程都可以往消息队列里面添加消息的,在添加同步屏障的时候,子线程往消息队列头部添加了一个耗时的message,执行到屏障消息的时候,UI刷新已经发送了无数的异步消息了,并且都没有被执行,就会出现掉帧。

这边举一个生动的例子,屏障消息就好像是交警,异步消息就好像是政府车辆,同步消息就是好像是我们的私家车。上午9点政府车辆想从这条路通过,9点之前交警封好路就行了,9点之前的私家车正常通过,9点之后的私家车需要等政府车辆全部通过后才能过马路。

所以同步屏障不需要放在队列的头部,根据时间顺序入队列就行,但是一旦他们进入队列,后面只能执行异步消息了,后面的同步消息全部被拦截在马路外面了。

我们来看一下消息是怎么取出来的:

@UnsupportedAppUsage
    Message next() {
      ......
        for (;;) {
           ......

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

msg.target等于空为屏障,当发现屏障消息的时候,会一直循环查找下一个异步消息,保障先执行异步消息。

当异步消息执行后,马上会发一个消息去移除屏障消息,否则会一直循环。屏障消息和异步消息一定是成对出现的。

  • 23
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值