其他分享
首页 > 其他分享> > 什么是Handler的同步屏障机制?,android适配器模式

什么是Handler的同步屏障机制?,android适配器模式

作者:互联网

正常插入消息会调用enqueueMessage方法,同时将handler赋值给message的target。

//将消息插入消息队列

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

}

在MessageQueue中进行判断,如果target为空也就是这个message没有对应的handler则会报异常。

boolean enqueueMessage(Messag
e 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.");

}

// 如果需要唤醒,则唤醒

if (needWake) {

nativeWake(mPtr);

}

通过MessageQueue的postSyncBarrier方法插入屏障,message的target属性为null

private int postSyncBarrier(long when) {

synchronized (this) {

final int token = mNextBarrierToken++;

//msg没有为target属性赋值

final Message msg = Message.obtain();

//根据时间插入到MessageQueue中

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;

}

}

经过以上的操作,我们可以总结出

如何发送异步消息

通常我们发送的都是普通消息,如果想发送异步消息

public Handler(boolean async) {

this(null, async);

}

public Handler(@NonNull Looper looper, @Nullable Callback callback) {

this(looper, callback, false);

}

public Handler(@Nullable Callback callback, boolean async) {

mLooper = Looper.myLooper();

if (mLooper == null) {

throw new RuntimeException(

"Can’t create handler inside thread " + Thread.currentThread()

}

mQueue = mLooper.mQueue;

mCallback = callback;

mAsynchronous = async;

}

public void setAsynchronous(boolean async) {

if (async) {

flags |= FLAG_ASYNCHRONOUS;

} else {

flags &= ~FLAG_ASYNCHRONOUS;

}

}

消息处理的过程

MessageQueue是通过next方法来遍历消息的

@UnsupportedAppUsage

Message next() {

for (;

标签:异步,屏障,适配器,next,Handler,消息,msg,android,target
来源: https://blog.csdn.net/m0_66264856/article/details/122721562