Android的消息机制(Handler的工作原理)

Android的消息机制

Android中的消息机制其实也就是Handler的运行机制。Android中通过使用Handler来进行更新UI的操作。因为Android的UI更新是单线程模型,UI控件也都是非线程安全的。其原因是如果给UI控件加锁,那么效率将会变得底下的同时还会将UI访问的逻辑变得复杂。

Handler的运行基于MessageQueueLooper的支撑。MessageQueue顾名思义是消息队列。但其实是一个单项链表结构来存储信息Message的。而Looper则是不断去读取消息队列MessageQueue中的信息,将其交与发送该消息的HandlerdispatchMessage进行处理。

下面我们就HandlerMessageQueueLooper分别分析一下其各自的工作原理。


MessageQueue

消息队列中维护了一个Message类型的变量mMessagesMessage是链表结构,所以之前所说消息队列是通过单项链表结构来存储消息。
当消息队列收到来自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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值