added in API level 1
Handler
public class Handler
extends Object
java.lang.Object | |
↳ | android.os.Handler |
Known direct subclasses AsyncQueryHandler, AsyncQueryHandler.WorkerHandler, HttpAuthHandler, SslErrorHandler |
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允许你去发送和处理Message
对象和与线程的MessageQueue对象相关的可运行对象。每个Handler实例关联一个单个的线程和线程的消息队列。当创建一个新的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)计划在将来某个时刻调度消息或者执行可运行的任务;
(2)在不同的线程中执行入队的动作而不是在单线程中。
Scheduling messages is accomplished with the post(Runnable)
, postAtTime(Runnable, long)
,postDelayed(Runnable, Object, long)
, sendEmptyMessage(int)
, sendMessage(Message)
, sendMessageAtTime(Message, long)
, and sendMessageDelayed(Message, long)
methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message
object containing a bundle of data that will be processed by the Handler's handleMessage(Message)
method (requiring that you implement a subclass of Handler).
消息调度是通过post(Runnable)
, postAtTime(Runnable, long)
,postDelayed(Runnable, Object, long)
, sendEmptyMessage(int)
, sendMessage(Message)
, sendMessageAtTime(Message, long)
, 和 sendMessageDelayed(Message, long)方法完成的。post方法允许你对在消息队列里被调用的Runnable对象进行排队当它们被接收时,
sendMessage 方法允许你
对包含数据的Message对象进行排队,它们将会被Handler的handleMessage(Message)方法处理(需要实现Handler的子类)。
When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior.