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中。
整体结构如下图(来源于网络):