构造一个异步消息
Message.setAsynchronous(true)
Sync Barrier
SyncBarrier是通过MessageQueue中的postSyncBarrier(long when)、removeSyncBarrier(int token)调用来实现添加、删除的,用于控制异步消息的执行。
MessageQueue.next()
-
class MessageQueue {
-
Message next() {
-
// ...
-
// 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());
-
}
-
// ...
-
}
-
}
Looper在获取下一个Message时,如果在队列头部遇到一个SyncBarrier时,则直接跳过后面的同步Message,直奔下一个异步消息。
使用
SyncBarrier在ViewRootImpl执行Traversals相关的代码时有被设置。
当设置一个View属性时,会逐层向上调用到ViewRootImpl.invalidate,从而调用scheduleTraversals,其中设置了一个SyncBarrier。
之后由Vsync信号发送的用于遍历View(重新布局和绘制)的异步消息会高优先级执行。这个一步消息在执行doTraversal时,则将SyncBarrier再移除掉。
-
class ViewRootImpl {
-
final class TraversalRunnable implements Runnable {
-
@Override
-
public void run() {
-
doTraversal();
-
}
-
}
-
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
-
void scheduleTraversals() {
-
if (!mTraversalScheduled) {
-
mTraversalScheduled = true;
-
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
-
mChoreographer.postCallback(
-
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
-
if (!mUnbufferedInputDispatch) {
-
scheduleConsumeBatchedInput();
-
}
-
notifyRendererOfFramePending();
-
pokeDrawLockIfNeeded();
-
}
-
}
-
void unscheduleTraversals() {
-
if (mTraversalScheduled) {
-
mTraversalScheduled = false;
-
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
-
mChoreographer.removeCallbacks(
-
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
-
}
-
}
-
void doTraversal() {
-
if (mTraversalScheduled) {
-
mTraversalScheduled = false;
-
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
-
if (mProfile) {
-
Debug.startMethodTracing("ViewAncestor");
-
}
-
performTraversals();
-
if (mProfile) {
-
Debug.stopMethodTracing();
-
mProfile = false;
-
}
-
}
-
}
-
}
参考:《Android源码分析之Message》
http://www.cnblogs.com/zhaoxiaowei/p/3660245.html
扩展阅读:《Android Project Butter分析》 http://blog.csdn.net/innost/article/details/8272867