Android的消息机制
Android中的消息机制其实也就是Handler
的运行机制。Android中通过使用Handler
来进行更新UI的操作。因为Android的UI更新是单线程模型,UI控件也都是非线程安全的。其原因是如果给UI控件加锁,那么效率将会变得底下的同时还会将UI访问的逻辑变得复杂。
Handler的运行基于MessageQueue
和Looper
的支撑。MessageQueue
顾名思义是消息队列。但其实是一个单项链表结构来存储信息Message
的。而Looper
则是不断去读取消息队列MessageQueue
中的信息,将其交与发送该消息的Handler
去dispatchMessage
进行处理。
下面我们就Handler
、MessageQueue
和Looper
分别分析一下其各自的工作原理。
MessageQueue
消息队列中维护了一个Message
类型的变量mMessages
,Message
是链表结构,所以之前所说消息队列是通过单项链表结构来存储消息。
当消息队列收到来自Handler的消息时,消息队列需要将此条消息插入队列中也即mMessages
中。消息插入顺序和它的执行之间相关。
boolean enqueueMessage(Message msg, long 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.
needWeke = 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()){
neesWake = false;
}
}
msg.next = p; ///把消息插入到消息队列的头部
prev.next = msg;
}
if(neesWake){
nativeWake(mPtr);
}
}
return true;
}
主要是进行了消息的单链表插入,现在我们再来看下新的函数读取函数`next()。
...
for(;;){
...
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target