android的Handler工作原理

1、handler运行图

 handler    

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

 

以上的一段话说明了handler的一个运行原理,实际上,通过实验,每一个应用程序启动过后,系统会自动为它创建相应的looper对象,looper对象生成messagequeue对象,并将该应用程序所有的activity与messagequeue对象进行相应的绑定,而handler则是与某个生成它的线程绑到一起的,一般是ui线程,handler通过发送message对象到messagequeue对象里面,并通过looper对象的不断循环,以对每个message对象进行相应的处理,以达到异步更新ui线程里面的一些控件。

 

 以下对运行机制的解释

疑问一:

 凭什么说该应用程序所有activity只有一个looper对象,一个messagequeue对象?

原因:其实这个问题可以通过实验验证,可以通过调用不同activity方法getMainLooper()对象,其实都是一个,再者messagequeue对象是由looper对象生成,所以当然一样且有一个。(looper对象由系统维护)

疑问二:

从messagequeue队列中出来的message为啥知道调用哪个handler呢?

 

    /**
     * User-defined message code so that the recipient can identify
     * what this message is about. Each {@link Handler} has its own name-space
     * for message codes, so you do not need to worry about yours conflicting
     * with other handlers.
     */
    public int what;

 

其实就是这个what,它对接受者进行唯一标识,每个message对象有它自己的命名空间,所以message对象调用handler不会产生冲突。

疑问三:

以上图中的thread与handler有联系吗?

我画的handler对象源于主线程,之所以开子线程是为了在进行一些长时间的操作,如下载,网络操作等,避免出现ANR现象,同时又可以保证实时对ui线程进行控件更新操作(如进度条更新)。所以两者没有必然的联系,看情况而定。

补充:

其实新开的子线程默认是没有looper对象的,所以也就不存在相应的messagequeue对象,如果子线程里面有自己生成的handler对象,那么只有当它里面存在looper对象时,才可进行消息的接收

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值