android.od.Handler是android SDK 处理定时操作的核心类。能够完成异步操作。
通过Handler类,可以提交和处理一个Runnable对象。
这个对象的run方法可以立即执行,也可以在指定的时间执行。
handler类允许你发送消息和处理线程队列中的消息及Runnable对象。
handler实例都是与一个线程和该线程的消息队列一起使用的。一旦创建一个新的handler的实例,系统就会把该实例与一个线程和该线程的消息队列捆绑起来,才可以发送消息和Runnable对象给消息队列,并在消息队列的出口处 处理它们;
handler在把runnable对象放到队列中之后运行的时候,他不是生成另外一个线程来运行的;
下面是几个常用的方法:
post
public final boolean post(Runnable r)
- Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
- 将一个Runnable对象r,放到消息队列中去。当handler逮到它的时候,将会在线程里面运行。
postDelayed
public final boolean postDelayed(Runnable r, long delayMillis)
- Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.
- 把一个Runable的对象放到消息队列中,并且在时间delayMillis之后,运行。
sendMessage
public final boolean sendMessage(Message msg)
-
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in
handleMessage(android.os.Message)
, in the thread attached to this handler. - 将一个消息,放到队列的尾端。将会被handleMessage(msg)方法取得
handleMessage
public void handleMessage(Message msg)
- Subclasses must implement this to receive messages.
- 在子类中,这个方法必须被实现,才能用于接收消息
removeCallbacks
public final void removeCallbacks(Runnable r)
- Remove any pending posts of Runnable r that are in the message queue.
- 把队列里面的Runnable对象移除。清空