handler与message(三)

来源:互联网 发布:ck jeans 知乎 编辑:程序博客网 时间:2024/05/22 13:14

Handler

Class Overview

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(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).


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

翻译:

一个处理程序允许您发送和处理消息和Runnable对象与线程的MessageQueue相关联。每个处理程序实例相关联的单个线程和线程的消息队列。当你创建一个新的处理程序,它绑定到线程/线程的消息队列创建它——从那时起,它将提供消息和可运行,消息队列和执行他们的消息队列


处理程序有两个主要用途:(1)调度信息和运行的执行是在将来的某个时间点;和(2)排队一个动作比你自己的一个不同的线程上执行。


调度信息完成后(可运行),postAtTime(Runnable,长),postDelayed(Runnable,长),sendEmptyMessage(int),sendMessage(消息),sendMessageAtTime(消息,长),和sendMessageDelayed(消息,长)方法。发布版本允许您将Runnable对象被称为由消息队列时收到;sendMessage版本允许您将一个消息对象包含一个包的数据将被处理程序处理的handleMessage(消息)方法(处理程序要求您实现一个子类)。


发布或发送到处理程序时,您可以允许项目尽快处理消息队列准备这样做,或指定一个延迟之前加工处理或绝对时间。后两个允许您实现超时,蜱虫,和其他时序为基础的行为。


为应用程序创建进程时,其主要致力于运行一个线程消息队列,负责管理顶级应用程序对象(活动、广播接收器等)和他们创建的任何windows。您可以创建自己的线程,并且与主应用程序线程通信通过一个处理程序。这是通过调用相同的帖子或sendMessage方法和之前一样,但从你的新线程。给定的Runnable或消息将被安排在处理程序的消息队列,并在适当的时候处理。





0 0
原创粉丝点击