加入收藏 | 设为首页 | 会员中心 | 我要投稿 网站开发网_马鞍山站长网 (https://www.0555zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 业界 > 正文

Android消息机制Handler,有必要再讲一次

发布时间:2019-07-26 05:13:24 所属栏目:业界 来源:Engineers
导读:副标题#e# 我们在日常开发中,总是不可避免的会用到 Handler,虽说 Handler 机制并不等同于 Android 的消息机制,但 Handler 的消息机制在 Android 开发中早已谙熟于心,非常重要! 通过本文,你可以非常容易得到一下问题的答案: Handler、Looper、Message

从入队消息 enqueueMessage() 的实现来看,它的主要操作其实就是单链表的插入操作,这里就不做过多的解释了,我们可能应该更多的关心它的出队操作方法 next():

  1. Message next() { 
  2.  // ... 
  3.  int nextPollTimeoutMillis = 0; 
  4.  for (;;) { 
  5.  // ... 
  6.  nativePollOnce(ptr, nextPollTimeoutMillis); 
  7.  synchronized (this) { 
  8.  // Try to retrieve the next message. Return if found. 
  9.  final long now = SystemClock.uptimeMillis(); 
  10.  Message prevMsg = null; 
  11.  Message msg = mMessages; 
  12.  if (msg != null && msg.target == null) { 
  13.  // Stalled by a barrier. Find the next asynchronous message in the queue. 
  14.  do { 
  15.  prevMsg = msg; 
  16.  msg = msg.next; 
  17.  } while (msg != null && !msg.isAsynchronous()); 
  18.  } 
  19.  if (msg != null) { 
  20.  if (now < msg.when) { 
  21.  // Next message is not ready. Set a timeout to wake up when it is ready. 
  22.  nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); 
  23.  } else { 
  24.  // Got a message. 
  25.  mBlocked = false; 
  26.  if (prevMsg != null) { 
  27.  prevMsg.next = msg.next; 
  28.  } else { 
  29.  mMessages = msg.next; 
  30.  } 
  31.  msg.next = null; 
  32.  if (DEBUG) Log.v(TAG, "Returning message: " + msg); 
  33.  msg.markInUse(); 
  34.  return msg; 
  35.  } 
  36.  } else { 
  37.  // No more messages. 
  38.  nextPollTimeoutMillis = -1; 
  39.  } 
  40.  //... 
  41.  } 
  42.  //... 
  43.  // While calling an idle handler, a new message could have been delivered 
  44.  // so go back and look again for a pending message without waiting. 
  45.  nextPollTimeoutMillis = 0; 
  46.  } 

(编辑:网站开发网_马鞍山站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!