Handler MessageQueue Message Looper关系浅析

本文详细介绍了Android系统中用于线程间通信的核心组件Handler、Message和MessageQueue的作用与机制,包括它们如何安排消息和Runnable对象在未来执行,以及如何在非当前线程上执行操作。此外,文章还阐述了Looper的作用及其与MessageQueue的关系,并提供了关键概念的总结,帮助开发者更好地理解和运用这些机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1、Handler

	/**
	 * 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允许你通过一个线程类MessageQueue来发送和处理Message、Runnable对象,每一个Handler实例都与一个单线程以及该单线程的消息队列相关联。

	/**
	 * There are two main uses for a Handler: (1) to schedule messages and
	 * runnables to be executed as some point in the future; and (2) to enqueue
	 * an action to be performed on a different thread than your own.
	 */

 Handler的两个作用就是: 

1)安排消息和Runnable对象在未来某个时间点执行

2)在非当前线程上来执行一个排到的动作

注意第二个作用,当我们需要做一些耗时的动作时,不一定要用线程或异步来完成,使用Handler同样可以达到目的。

2、Message

	/**
	 * Defines a message containing a description and arbitrary data object that
	 * can be sent to a {@link Handler}. This object contains two extra int
	 * fields and an extra object field that allow you to not do allocations in
	 * many cases.
	 * 
	 * While the constructor of Message is public,<span style="color:#ff0000;"> the best way to get one of
	 * these is to call {@link #obtain Message.obtain()} or one of the
	 * {@link Handler#obtainMessage Handler.obtainMessage()}</span> methods, which will
	 * pull them from a pool of recycled objects.
	 */

MessageQueue中存放的消息对象,官方推荐使用Message.obtain()或者Handler.obtainMessage()来从Message Pool中获取可回收的Message对象。


3、MessageQueue

1)用来存放Message的消息队列,是一种数据结构。

2)每一个线程最多只能拥有一个MessageQueue数据结构

3)主线程创建时,会创建一个默认的Looper对象,而Looper对象的创建,将自动创建一个Message Queue。其他非主线程,不会自动创建Looper,要需要的时候,通过调用prepare函数来实现。


4、Looper

1)MessageQueue的管理者,每一个Looper都与一个线程相关,创建一个Looper同时会创建一个MessageQueue结构

2)除了主线程有自己默认的Looper外,其他线程需要自定义一个Looper才能接受Message。

3)Looper从MessageQueue中取出Message然后,交由Handler的handleMessage进行处理。处理完成后,调用Message.recycle()将其放入Message Pool中。

整体结构如下图(来源于网络):





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值