Handler,MessageQueue,Message 【译】

 android.os.Handler

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.

 

 

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.

Scheduling messages is accomplished with the post, postAtTime(Runnable, long), postDelayed, sendEmptyMessage, sendMessage, sendMessageAtTime, and sendMessageDelayed 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 method (requiring that you implement a subclass of 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.

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 than be scheduled in the Handler's message queue and processed when appropriate.

      一个Handler(句柄)用于发送处理Message(消息)以及 关联到一个线程的MessageQueue(消息队列)的Runnable (可运行)对象。每个Handler实例关联一个线程以及该线程的消息队列。当创建一个新的Handler,它被绑定到创建它的线程/该线程的消息队列——此后,它将发送消息s或者runables(可运行对象)到该消息队列,并且他们将像来自于消息队列将被执行。

      Handler的2个主要用途:(1)在未来某个时间点,调度消息s或者可执行对象s(runables)。(2)把另一个线程需要执行的任务放入队列。调用 post, postAtTime(Runnable, long), postDelayed, sendEmptyMessage, sendMessage, sendMessageAtTime, and sendMessageDelayed 这几个方法,调度消息便完成。

Post开头的方法,当收到消息后,Runnable对象将被放入消息队列以供执行,Send开头的方法将放入Message 对象,该对象携带数据集,并被Handlder'shandleMessage方法(需要自行实例化Handler子类)。

     

     当post或者send一个Handler时,可以指定立即被执行还是将来某个特定时间点(相对于现在的延迟时间或者绝对时间点)执行。后一种方法,可以指定超时、时钟计数ticks,和其他基于时间的行为。

   当一个进程被创建,它的主线程便开始运行消息队列,消息队列它管理顶级应用程序对象(Activity,Braoadcast receiver等)以及他们创建的窗体。可以通过创建新线程并使用Handler实现与应用程序的主线程通信,具体可通过在这新线程内调用前述的post和sendMessage类方法来实现。Runnable或者Message会被Handler的消息队列调度,并适时被执行。

猜你喜欢

转载自lvdccyb.iteye.com/blog/1256339
今日推荐