Android Handler源码解析

本文主要解析Android Handler的源码,探讨其如何接收并处理消息,以及与Looper、Message的关系。Handler作为线程与消息队列的接口,创建时会关联到当前线程及其消息队列,用于异步通信。
摘要由CSDN通过智能技术生成

上一篇的地址为 Android Looper源码解析

一、讲解:

Android中的Handler是用来接受消息,并处理消息中的内容。它可以看成是一个线程的接口,当给它发送消息时,其对应的线程便会处理消息。

Google的介绍为:

  A Handler allows you to send and process {@link Message} and Runnable
  objects associated with a thread's {@link 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允许你发送一个消息或者Runnable代码块给其关联的线程的消息队列,每个Handler的示例都关联着其线程和线程的消息队列。即当你创建一个新的Handler时,它关联了创建的线程和其线程中的消息队列,之后,它就可以发送一个消息或者Runnable代码块给其关联的消息队列。当消息队列弹出对应消息时,Handler也会执行它


带着问题去看源码是最好的方法,那么我们的问题是:

  1、 为什么每个Handler初始话时在哪个线程就是哪个线程的接口?
  2、sendMessage如何执行的? 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值