Handler 消息机制小结
线程的Looper对象只有一个,在线程中调用Looper.myLooper() 只有在调用Looper.prepare(),才会在ThreadLocal中去创建looper对象 并且存在ThreadLocal中。
想能处理消息,需要调用Looper.looper() 方法开启轮询
Looper对象中存放了MessageQueue
Message
target->handler
new Message() 中 target->this handler
MessageQueue
Message单链表结构
插入链表的消息按照 延迟时间 + 当前时间排序
可以添加IdleHandler
IdleHandler -> Gc
当MessageQueue没有消息时候执行
当前消息是延迟消息,并且没有达到延迟时间时候
queueIdle 返回false 单词执行,返回true循环执行
延迟实现
当前消息是延迟消息,且时间未达到,**MessageQueue.next()**进入线程阻塞
计算需要延迟的时间 nextPollTimeoutMillis
nativePollOnce(ptr, nextPollTimeoutMillis) 定时唤醒当前线程执行
通过native层设置epoll_wait的超时事件
Handler 同步屏障问题:
Handler中的消息分为同步消息、异步消息两类
Handler.mAsynchronous变量
在View绘制时,会在Looper中使用同步屏障,来确保在view下一帧绘制完之前其他同步消息都暂不处理。
异步消息不受同步屏障限制
ViewRootImpl 中会添加一个target == null的消息,判断条件即为null为异步消息