本文一点一点的把与handler相关的知识点都引了出来,尽最大努力把这个机制讲清楚。
为什么android要求子线程通过Handler来更新UI
我们先来看看官网[https://developer.android.com/training/multiple-threads/communicate-ui.html#Handler]的这段文字:
Every app has its own special thread that runs UI objects such as View objects; this thread is called the UI thread. Only objects running on the UI thread have access to other objects on that thread. Because tasks that you run on a thread from a thread pool aren’t running on your UI thread, they don’t have access to UI objects. To move data from a background thread to the UI thread, use a Handler that’s running on the UI thread.
总的意思是:app启动总是会创建一个单独主线程UI线程,约定组件操作只能再UI线程中完成,其它线程需要操作组件时,需借助Handler来完成。
Handler功能
- [https://developer.android.com/reference/android/os/Handler.html]上的文字:
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允许你发送和处理与线程的MessageQueue有关的message和runnable对象,一个handler对象只能和一个thread有关,每一个handler的创建一定会绑定一个thread或message queue;从那时起,创建handler的线程将会发送message和runnable到message queue,而主线程会从message queue中取出来处理。 - 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) message和runnable会在将来的某个时间点执行;(2) 需要再另一个线程中添加入队动作,不是本线程。 - Handler是线程管理框架的一部分,主要是接收子线程发送的数据,并用此数据配合主线程更新UI,用来跟UI主线程交互用。
- 比如在子线程处理一些耗时的操作,然后子线程用handler发送一个message给主线程UI线程的handler来接收、处理该消息更新UI,这样以避免直接在UI主线程中处理事务导致影响UI主线程的其他处理工作,Android提供了Handler作为主线程和子线程的纽带;
- 也可以将handler对象传给其他进程,以便在其他进程中通过handler给你发送事件;
- 还可以通过handler的延时发送message,可以延时处理一些事务的处理。
创建Handle
- Handler():
Default constructor associates this handler with the Looper for the current thread. - Handler(Handler.Callback callback):
Constructor associates this handler with the Looper for the current thread and takes a callback interface in which you can handle messages. - Handler(Looper looper):
Use the provided Looper instead of the default one. - Handler(Looper looper, Handler.Callback callback):
Use the provided Looper instead of the default one and take a callback interface in which to handle messages.
创建looper
上面的4个构造方法中,会发现每一个构造方法都会有一个looper类。先来说说looper类
API中提到:This class contains the code required to set up and manage an event loop based on MessageQueue
意思是Looper类包含了需要建立和管理一个基于MessageQueue的事件代码
[