Handler类介绍(中文文档)

Handler用法

一、Handler的定义

主要接受子线程发送的数据,并用此数据配合主线程更新UI。

当应用程序启动时,Android首先会开启一个主线程 (即UI线程),主线程管理界面中的UI控件,进行事件分发,比如说:点击Button,Android系统会分发事件到Button上,来响应你的操作。如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,如果你放在主线程中的话,界面会出现假死现象,如果5秒钟还没有完成的话,会收到Android系统的一个错误提示“强制关闭”。这个时候我们需要把这些耗时的操作,放在一个子线程中。

因为子线程涉及到UI更新,Android主线程是线程不安全的,也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。这个时候,Handler就出现了。来解决这个复杂的问题,由于Handler运行在主线程中(UI线程中), 它与子线程可以通过Message对象来传递数据,这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传递Message对象,(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。

二、Handler一些特点

public class Handler extends Object

java.lang.object à android.os.Handler

已知直接子类:

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(消息队列)的Runnable对象,每一个Handler实例都与一个单独的线程和该线程的消息队列相关。当你创建一个新的Handler,它被绑定到创建它的线程/消息队列线程中。从这一点上来说,它将传递消息和runnable对象,并且执行他们,因为他们来自于消息队列中。

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、安排messages和runnables在将来的某些点上执行;2、排列一个将来执行的动作在一个不同的线程中

Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, 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).

安排messages是通过 post(Runnable), postAtTime(Runnable, long),

postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long)方法来完成的。The post versions允许你排列Runnable对象被接收到的消息队列所调用;the sendMessage versions允许您排列一个包含了大量将被Handler的handleMessage(Message)方法处理的数据的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.

当posting或sending一个Handler,您可以允许item当message对列一准备就绪就进行处理,你也可以在它被处理之前指定一个延迟或绝对时间对它进行处理。后两个允许您实现超时和其他以时序为基础的行为。

When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.

当一个进程在你的应用中被创建,它的主线程致力于运行一个负责管理顶级应用程序对象(如:活动、广播接收器等)和他们创建的任何windows的消息队列。您可以创建你自己的线程,通过Handler与主应用线程进行交互。这样都在之前通过调用的同一个post和sendMessage方法实现的,但是来自你的新线程。给定的Runnable或Message将被安排在Handler的message队列,并在适当的时候进行处理。

摘要

嵌套类

接口

Handler.Callback

Callback interface you can use when instantiating a Handler to avoid having to implement your own subclass of Handler.

实例化一个避免实现你自己子类的Handler的Handler时的回调接口。

Public Constructors(公共构造函数)

Handler()

Default constructor associates this handler with the queue for the current thread.

If there isn't one, this handler won't be able to receive messages.

将handler和当前线程的队列联系起来的默认构造函数。如果不是一个,该handler将不能接收消息。

Handler(Handler.Callback callback)

Constructor associates this handler with the queue for the current thread and takes a callback interface in which you can handle messages.

将handler和当前线程的队列和你能处理消息的回调接口联系起来的构造函数。

Handler(Looper looper)

Use the provided queue instead of the default one.

用提供的对列代替默认的。

Handler(Looper looper, Handler.Callback callback)

Use the provided queue instead of the default one and take a callback interface in which to handle messages.

用提供的对列代替默认的,处理消息的回调接口。

Public Methods(公共方法)

void

dispatchMessage(Message msg)

Handle system messages here.

这里处理系统的消息。

final void

dump(Printer pw, String prefix)

final Looper

getLooper()

String

getMessageName(Message message)

Returns a string representing the name of the specified message. The default implementation will either return the class name of the message callback if any, or the hexadecimal representation of the message "what" field.

返回一个代表指定消息名字的字符串。它的默认实现将返回这个回调消息的类名,或者这个消息“what”字段的十六进制的代表。

void

handleMessage(Message msg)

Subclasses must implement this to receive messages.

子类必须实现它用来接收消息。

final boolean

hasMessages(int what, Object object)

Check if there are any pending posts of messages with code 'what' and whose obj is 'object' in the message queue.

检查是否有任何即将post带代码“what”和它的obj 是“object”的消息在消息队列。

final boolean

hasMessages(int what)

Check if there are any pending posts of messages with code 'what' in the message queue.

检查是否有任何即将post带代码“what”的消息在消息队列。

final Message

obtainMessage(int what, int arg1, int arg2)

Same as obtainMessage(), except that it also sets the what, arg1 and arg2 members of the returned Message.

与obtainMessage()方法一样,除此之外它也能设置what,arg1和arg2返回消息的成员。

final Message

obtainMessage()

Returns a new Message from the global message pool. More efficient than creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this). If you don't want that facility, just call Message.obtain() instead.

从全局消息池中返回一个新的消息。比创建和分配新的实例有效率。这个的重新取回的消息有它的handler设置到这个实例。如果你不想要那套设施,可以通过调用的Message.obtain() 方法替代。

final Message

obtainMessage(int what, int arg1, int arg2, Object obj)

Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message.

与obtainMessage()方法一样,除此之外它也能设置what,obj,arg1和arg2返回消息值。

final Message

obtainMessage(int what)

Same as obtainMessage(), except that it also sets the what member of the returned Message.

与obtainMessage()方法一样,除此之外它也能设置what返回消息成员。

final Message

obtainMessage(int what, Object obj)

Same as obtainMessage(), except that it also sets the what and obj members of the returned Message.

与obtainMessage()方法一样,除此之外它也能设置obj返回消息成员。

final boolean

post(Runnable r)

Causes the Runnable r to be added to the message queue.

使Runnable r添加到消息队列。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

final boolean

postAtFrontOfQueue(Runnable r)

Posts a message to an object that implements Runnable.

发布一个消息到一个实现了Runnable的对象。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

final boolean

postAtTime(Runnable r, Object token, long uptimeMillis)

Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis.

使Runnable r添加到消息队列中,运行在一个uptimeMillis给出的特定时间。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。注意true的结果并不意味着Runnable将被执行,如果的这个looper在发送消息之前放弃了,这个消息将被放弃。

final boolean

postAtTime(Runnable r, long uptimeMillis)

Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis.

使Runnable r添加到消息队列中,运行在一个uptimeMillis给出的特定时间。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。注意true的结果并不意味着Runnable将被执行,如果的这个looper在发送消息之前放弃了,这个消息将被放弃。

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.

使Runnable r添加到消息队列,运行在指定时间的流逝之后。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。注意true的结果并不意味着Runnable将被执行,如果的这个looper在发送消息之前放弃了,这个消息将被放弃。

final void

removeCallbacks(Runnable r)

Remove any pending posts of Runnable r that are in the message queue.

移除任何即将发布的在消息队列里的Runnable r。

final void

removeCallbacks(Runnable r, Object token)

Remove any pending posts of Runnable r with Object token that are in the message queue.

移除任何即将发布的有Object token在消息队列里的Runnable r。

final void

removeCallbacksAndMessages(Object token)

Remove any pending posts of callbacks and sent messages whose obj is token.

移除任何即将发布的回调和发送obj是token的消息。

final void

removeMessages(int what)

Remove any pending posts of messages with code 'what' that are in the message queue.

移除任何即将发布的有代码“what”的在消息队列中的消息。

final void

removeMessages(int what, Object object)

Remove any pending posts of messages with code 'what' and whose obj is 'object' that are in the message queue.

移除任何即将发布的有代码“what”和它的obj是“object”的在消息队列中的消息。

final boolean

sendEmptyMessage(int what)

Sends a Message containing only the what value.

发送一个仅包含what值的消息。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

final boolean

sendEmptyMessageAtTime(int what, long uptimeMillis)

Sends a Message containing only the what value, to be delivered at a specific time.

发送一个仅包含what值的将在一个特定时间送达的消息。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

final boolean

sendEmptyMessageDelayed(int what, long delayMillis)

Sends a Message containing only the what value, to be delivered after the specified amount of time elapses.

发送一个仅包含what值的将在特定的时间流逝后送达的消息。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

final boolean

sendMessage(Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time.

将一个消息推到当前时间之前的所有挂起的消息之后的消息队列的最后。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

final boolean

sendMessageAtFrontOfQueue(Message msg)

Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop. You will receive it in handleMessage(Message), in the thread attached to this handler. This method is only for use in very special circumstances -- it can easily starve the message queue, cause ordering problems, or have other unexpected side-effects.

排列一个在消息队列前面的消息,处理下一个message loop的迭代。你将在附属于这个handler的线程里的handleMessage(Message)方法里接收到它。这个方法只能在特殊的情况下使用,它很容易饿死消息队列,引起排序问题,或者还有其他意想不到的副作用。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。

boolean

sendMessageAtTime(Message msg, long uptimeMillis)

Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds) uptimeMillis. The time-base is uptimeMillis(). You will receive it in handleMessage(Message), in the thread attached to this handler.

排列一个消息进入在绝对时间之前的所有的挂起的消息之后的消息队列。时间坐标是uptimeMillis()。你将在附属于这个handler的线程里的handleMessage(Message)方法里接收到它。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。注意true的结果并不意味着Runnable将被执行,如果的这个looper在发送消息之前放弃了,这个消息将被放弃。

final boolean

sendMessageDelayed(Message msg, long delayMillis)

Enqueue a message into the message queue after all pending messages before (current time + delayMillis). You will receive it in handleMessage(Message), in the thread attached to this handler

排列一个消息进入在(当前时间+延迟时间)之前的所有的挂起的消息之后的消息队列。你将在附属于这个handler的线程里的handleMessage(Message)方法里接收到它。

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

如果Runnable被成功放置在消息队列中就返回true,如果失败就返回false,常常因为the looper处理消息队列正在退出。注意true的结果并不意味着Runnable将被执行,如果的这个looper在发送消息之前放弃了,这个消息将被放弃。

String

toString()

Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:

   getClass().getName() + '@' + Integer.toHexString(hashCode())

See Writing a useful toString method if you intend implementing your own toString method.

返回一个包含该对象的简洁的、可读的描述性的字符串。在子类鼓励覆写这个方法,提供一个了解这个对象的类型和数据的实现。默认的实现相当于下面的表达式:

getClass().getName() + '@' + Integer.toHexString(hashCode())

如果你想实现你自己的toString方法,看看写一个有用的toString方法。

Inherited Methods(继承方法)

From class java.lang.Object(Object类)

Object

clone()

Creates and returns a copy of this Object.

创建并返回这个对象的一个副本。

boolean

equals(Object o)

Compares this instance with the specified object and indicates if they are equal. 比较该实例与指定的对象,并表示他们是否相等。

void

finalize()

Invoked when the garbage collector has detected that this instance is no longer reachable.

当垃圾收集器发现这个实例不再是可获得的时候调用此方法。

final Class<?>

getClass()

Returns the unique instance of Class that represents this object's class.

返回代表这个对象的class的类的独特实例。

int

hashCode()

Returns an integer hash code for this object.

返回该对象的整数哈希值。

final void

notify()

Causes a thread which is waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up.

让一个正在等待该对象的监听器(通过调用wait()方法)的线程被唤醒。

final void

notifyAll()

Causes all threads which are waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up.

让所有正在等待该对象的监听器(通过调用wait()方法)的线程被唤醒。

String

toString()

Returns a string containing a concise, human-readable description of this object.

返回一个包含该对象的简洁的、可读的描述性的字符串。

final void

wait()

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

让该调用线程处于等待状态直到有另一个线程调用该对象的notify()或者notifyAll()方法。

final void

wait(long millis, int nanos)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires.

让该调用线程处于等待状态直到有另一个线程调用该对象的notify()或者notifyAll()方法或者是到指定的超时时限。

final void

wait(long millis)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires.

让该调用线程处于等待状态直到有另一个线程调用该对象的notify()或者notifyAll()方法或者是到指定的超时时限。

 

posted on 2012-09-27 14:37  Harvey Ren  阅读(4904)  评论(2编辑  收藏  举报

导航