Android Handler的用法

来源:互联网 发布:sql存储过程详细说明 编辑:程序博客网 时间:2024/05/16 15:22
package com.sean.demo.handler;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.util.Log;import android.widget.TextView;/** * Handler使用的例子。 * 1.创建handler对象 * 2.在线程中向handler中发送message * 3.在handleMessage中更新UI。 *  * @author shihongyang * */public class HandlerDemoActivity extends Activity {private MyHandler handler;private TextView textView;private static final String TAG = "INFO:";    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        textView = (TextView) findViewById(R.id.text);                handler = new MyHandler();//1.当创建handler对象时,绑定到当前线程和消息的队列中。        MyThread m = new MyThread();        new Thread(m).start();//2.启动线程    }            class MyHandler extends Handler{public MyHandler(){        }        public MyHandler(Looper L){    super(L);    }        @Overridepublic void handleMessage(Message msg) {// 该方法需要实现。super.handleMessage(msg);Bundle bundle = msg.getData();String message = bundle.getString("info");Log.i(TAG, "IN HANDLEMESSAGE.");Log.i(TAG, message);        //4.更新UI,Handler的主要作用。        textView.setText(message);}    }            class MyThread implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep(10000);//线程休眠10秒} catch (InterruptedException e) {e.printStackTrace();}Log.d(TAG, "IN RUN.");Message msg = new Message();Bundle boudle = new Bundle();boudle.putString("info", "I'm from MyThread.");msg.setData(boudle);HandlerDemoActivity.this.handler.sendMessage(msg); // 3.向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 the post(Runnable),postAtTime(Runnable, long),postDelayed(Runnable, long),sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message, long), andsendMessageDelayed(Message, long) methods. Thepost 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. 


原创粉丝点击