Frameworks层handler分析(一)

来源:互联网 发布:mac能玩天涯明月刀 编辑:程序博客网 时间:2024/05/16 09:15

1.  Handler简介

A Handler allows you to send and process Message and Runnable objects associated with a thread'sMessageQueue. 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 thepost(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; thesendMessage versions allow you to enqueue aMessage object containing a bundle of data that will be processed by the Handler'shandleMessage(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 samepost orsendMessage 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.

 

简单翻译一下,方便大家查看,翻译的的不准确的地方希望大家指正。

Handler允许开发者去发送和处理消息或实现runnalbe的对象(后面文中简称runnable)通过应用一个线程的消息队列。每一个handler实例与一个单独的线程和线程中的消息队列相关联。所以,当你构建一个handler的时候,它必然和创建它的线程和线程中的消息队列一一对应 –- 从这个点上来说,handler它将会把消息或runnable发送给相关的消息队列并且执行它们在它们到达消息队列顶部时。

Handler主要有两个用途:(1)设定消息或runnable在将来的确定时间点执行;(2)异步通讯(在其他线程执行的动作执行完毕后通知本线程更新)。

控制消息队列主要使用以下方法:

post(Runnable),postAtTime(Runnable, long),postDelayed(Runnable, long),sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message, long), andsendMessageDelayed(Message, long)

以post开头的方法允许你将runnalbe加入到队列中并会由消息队列在接受到的时候被调用;以sendMessage开头的方法允许你将包含一些数据的消息加入到队列中并且会被Handler使用handleMessage(Message)方法处理(前提是你必须实现一个Handler的子类)。

当使用post类方法或sendMessage类方法时,既可以消息队列准备好就立刻执行,也可以设定延时,还可以设定执行的绝对时间。在后两种方式中允许实现各种时间行为(延时,时钟嘀嗒等)。

当一个进程为你的应用创建成功后,它的主线程中运行着一个消息队列,这个消息队列负责最高等级的应用对象(activities, broadcast receivers, etc)和它们创建的界面。你可以创建自己的线程(不止一个)来和主线程通过handler通讯。这个种通讯使用前面介绍的方法,但是由你创建的新线程发出。Handler的消息队列将会接受并在合适的时间处理消息或runnalbe

2.  Handler 应用实例

2.1 任务延时执行

public class MyHanlerActivity extends Activity {    private static final String TAG = "MyHanler";    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        Handler myHandler = new Handler();        myHandler.post(new ActivityFlasher());    }        class ActivityFlasher implements Runnable{            @Override           public void run() {                    Log.d(TAG, "cibon---->post()works");                               }        }} 


 

2.2 异步通讯(此例来源于网络,谢谢作者)

          

public class MyHandlerActivity2 extends Activity {     Button button;     MyHandler myHandler;      protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.handlertest);          button = (Button) findViewById(R.id.button);         myHandler = new MyHandler();         // 当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据         // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象         // (2): 让一个动作,在不同的线程中执行.          // 它安排消息,用以下方法         // post(Runnable)         // postAtTime(Runnable,long)         // postDelayed(Runnable,long)         // sendEmptyMessage(int)         // sendMessage(Message);         // sendMessageAtTime(Message,long)         // sendMessageDelayed(Message,long)                // 以上方法以 post开头的允许你处理Runnable对象         //sendMessage()允许你处理Message对象(Message里可以包含数据,)          MyThread m = new MyThread();         new Thread(m).start();     }      /**     * 接受消息,处理消息 ,此Handler会与当前主线程一块运行     * */      class MyHandler extends Handler {         public MyHandler() {         }          public MyHandler(Looper L) {             super(L);         }          // 子类必须重写此方法,接受数据         @Override         public void handleMessage(Message msg) {             // TODO Auto-generated method stub             Log.d("MyHandler", "handleMessage......");             super.handleMessage(msg);             // 此处可以更新UI             Bundle b = msg.getData();             String color = b.getString("color");             MyHandlerActivity.this.button.append(color);          }     }      class MyThread implements Runnable {         public void run() {              try {                 Thread.sleep(10000);             } catch (InterruptedException e) {                 // TODO Auto-generated catch block                 e.printStackTrace();             }              Log.d("thread.......", "mThread........");             Message msg = new Message();             Bundle b = new Bundle();// 存放数据             b.putString("color", "我的");             msg.setData(b);              MyHandlerActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI          }     }


 

原创粉丝点击