这节主要介绍Message都有哪些类型以及作用。(以下分析都是基于android 12代码)
同步Message
同步Message自不必多说,默认创建的Message都是同步的。
同步屏障Message
同步屏障Message是什么?
同步屏障Message可以这样理解:创建这种类型的Message并且把它放入MessageQueue的mMessages链表中,当执行到这种类型的Message后,它会阻止它后面的所有同步Message执行(即使同步Message到了应该执行的时间),只允许它后面的异步Message执行。
执行同步屏障Message的代码在next方法中
MessageQueue#next
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//msg.target == null 代表是同步屏障Message
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
//下面的逻辑是从链表中依次去查询是异步类型的Message,找到则执行后面逻辑,否则不执行任何同步Message
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
//如果msg存在则执行
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代表需要等待MessageQueue中放入Message,否则一直等待
nextPollTimeoutMillis = -1;
}
省略代码......
}
省略代码......
}
}
因此同步屏障Message是需要和异步Message配合才有意义。
同步屏障Message的使用
创建同步屏障Message
MessageQueue#postSyncBarrier
public int postSyncBarrier() {
return postSyncBarrier(SystemClock.uptimeMillis());
}
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) {
//创建一个token,因为可能存在创建多个syncBarrier的情况,因此token就代表当前创建的syncBarrier
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
//token赋值给msg的arg1
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
//根据when值 找到syncBarrier需要存放的位置
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;
}
返回token
return token;
}
}
调用postSyncBarrier方法就可以创建一个同步屏障Message,并且返回一个token,这个token需要保存,因为在移除的时候需要用到。同步屏障Message和普通的Message没啥区别,除了Message的target属性为null。因此如果Message的target为null就可以断定这个Message是同步屏障Message。
移除同步屏障Message
因为这种类型的Message需要创建者移除,不移除那就会导致所有的同步Message没法执行。移除方法如下:
MessageQueue#removeSyncBarrier
//token:创建时候返回的token
public void removeSyncBarrier(int token) {
// Remove a sync barrier token from the queue.
// If the queue is no longer stalled by a barrier then wake it.
synchronized (this) {
Message prev = null;
Message p = mMessages;
//根据token和target==null来查找同步屏障Message
while (p != null && (p.target != null || p.arg1 != token)) {
prev = p;
p = p.next;
}
if (p == null) {
throw new IllegalStateException("The specified message queue synchronization "
+ " barrier token has not been posted or has already been removed.");
}
final boolean needWake;
if (prev != null) {
prev.next = p.next;
needWake = false;
} else {
mMessages = p.next;
needWake = mMessages == null || mMessages.target != null;
}
//把Message回收
p.recycleUnchecked();
// If the loop is quitting then it is already awake.
// We can assume mPtr != 0 when mQuitting is false.
//需要唤醒,则去唤醒
if (needWake && !mQuitting) {
nativeWake(mPtr);
}
}
}
如上调用removeSyncBarrier方法参数为创建时候返回的token就可以把同步屏障Message移除。
异步Message
异步Message:这里的异步容易让人产生误解,总以为这种类型的Message是可以并行执行多个的意思,其实不是。它和同步Message,同步屏障Message一样也都是按照Message的when属性值的大小在链表中排列的。
创建异步的方法特别简单,只需要调用Message的setAsynchronous方法即可。
异步Message需要和同步屏障Message结合使用,它俩谁也离不了谁。如果没有同步屏障Message,那异步Message和同步Message没有任何区别。
异步Message和同步屏障Message的组合主要是解决这类问题:比如当前有一些Message,它们的优先级要高于其他的Message,必须先执行完这批Message后才能执行优先级低的Message。其中一个应用场景就是在绘制view的时候用到,如下部分代码:
ViewRootImpl#scheduleTraversals
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
//创建同步屏障Message
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
上面代码在绘制之前创建了同步屏障Message,这样把当前所有可执行的同步Message都给阻止掉,因为绘制的优先级最高,假如让一些同步Message执行,若它们耗时,这完全会影响整个绘制流程,你说是绘制重要还是啥重要,整个界面都一片空白了,那肯定会被用户骂的。
Choreographer#onVsync
public void onVsync(long timestampNanos, long physicalDisplayId, int frame,
VsyncEventData vsyncEventData) {
try {
省略代码......
Message msg = Message.obtain(mHandler, this);
//设置Message为异步Message
msg.setAsynchronous(true);
mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
在Choreographer的onVsync方法中,收到vsync信号后,为了让绘制工作能高优先级执行,把Message设置为异步,因为ViewRootImpl的scheduleTraversals方法中已经加入同步屏障Message了,所以高优先级执行绘制操作。
idle ”Message“
idle ”Message“:它其实不是一个Message,可以把它看成一个伪Message,在MessageQueue的next方法进行第一次循环的时候,尝试去执行所有的idle ”Message“。
相应的代码如下:
MessageQueue#next
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
//pendingIdleHandlerCount赋值为-1 代表只有第一次循环的时候才去执行idle Message
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
省略代码......
// 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.
//进入循环之前,给pendingIdleHandlerCount赋值了-1,因此pendingIdleHandlerCount< 0并且没有可执行的Message时候,开始准备执行idle Message
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
//mIdleHandlers存放了所有的idle Message
pendingIdleHandlerCount = mIdleHandlers.size();
}
//没有可执行的idle Message,则不往下面执行
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.
//依次循环执行idle Message
for (int i = 0; i < pendingIdleHandlerCount; i++) {
//拿出IdleHandler
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
//调用idler的queueIdle方法,该方法会返回一个boolean值,代表是否移除:false则需要移除;否则不用移除
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
//需要移除,则从mIdleHandlers移除这个idler
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
//把pendingIdleHandlerCount赋值为0,代表下一次就不用执行idle Message了
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;
}
}
它对应的类如下:(其实是一个接口)
MessageQueue#IdleHandler
public static interface IdleHandler {
/**
* Called when the message queue has run out of messages and will now
* wait for more. Return true to keep your idle handler active, false
* to have it removed. This may be called if there are still messages
* pending in the queue, but they are all scheduled to be dispatched
* after the current time.
*/
boolean queueIdle();
}
添加一个idle ”Message“的方法如下:
MessageQueue#addIdleHandler
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
总结
到此Message的类型就介绍完毕,每种Message都有自己适用的场景,大家可以根据需要来使用相应的Message