Handler Looper MessageQueue 之间的关系

handler在安卓开发中常用于更新界面ui,以及其他在主线程中的操作。内部结构大概图为:

1、handler持有一个Looper对象,这个Looper对象可以是自定义子线程的Looper,也可以是默认MainLooper。Looper主要作用就是不断循环MessageQueue中的Message,回调Handler的dispatchMessage方法。源码:

final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity(); for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
} // This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
} //这里回调handler中的dispatchMessage方法
msg.target.dispatchMessage(msg); if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
} // Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
} msg.recycleUnchecked();
}

2、Handler还持有MessageQueue对象的引用,用于sendMessage时,将消息添加到MessageQueue中。这样Looper就可以获取到最新的message。Handler中的MessageQueue其实就是Looper的MessageQueue成员属性。

   public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

所以一个大致的流程就是:

1、Looper在在不断的获取MessageQueue消息,调用handler的dispatchMessage方法

2、Handler.postMessage就是往Looper的MessageQueue中添加Message,并且设置message.target为Handler本身

最新文章

  1. UITextFeild的用法
  2. webpack中output配置项中chunkFilename属性的用法
  3. Qt信号与槽应用实例一
  4. 关于使用ResultSet ---结果集没有当前行
  5. 【转】Android之NDK开发
  6. Java_Activiti5_菜鸟也来学Activiti5工作流_之入门简单例子(一)
  7. Java学习笔记-File类的基本方法
  8. dhtmlx之dhtmlXGrid显示数据 --大数据
  9. PHP学习之-数据库操作
  10. Python - 首字母大写(capwords) 和 创建转换表(maketrans) 具体解释
  11. Xamarin Android Gestures详解
  12. 关于SSDT
  13. 浅谈java中的&quot;==&quot;和eqals区别
  14. Visual Stdio 2017增加SVN支持
  15. 利用airbase-ng建立Soft AP
  16. php面试题整理(二)
  17. PTA——数列求和
  18. ReactiveX 学习笔记(11)对 LINQ 的扩展
  19. as3 三行三列 布满9个为一个界面
  20. Oracle 自增长id

热门文章

  1. 《并发编程的艺术》阅读笔记之Sychronized
  2. python 基础篇 错误和异常处理
  3. [wp]xctf newscenter
  4. Ubuntu 安装 Qt, 安装辅助软件
  5. 如何在mysql中实现自然排序
  6. Intellij IDEA 使用Spring-boot-devTools
  7. CF思维联系–CodeForces - 225C. Barcode(二路动态规划)
  8. CodeForces - 1047A
  9. unittest 中的方法调用时报错 ValueError: no such test method in &lt;class &#39;mytestcase.MyTestCase&#39;&gt;: runTest
  10. mysql查询表内所有字段名和备注