声明HandlerThread对象,实现了使用Looper来处理消息队列的功能
//这个类由Android操作系统提供
HandlerThread handlerThread = new HandlerThread("handler_Thread");
handlerThread.start();
//当前的myHandler对象使用looper线程处理消息
MyHandler myHandler = new MyHandler(handlerThread.getLooper());
Message msg = myHandler.obtainMessage();
//简单数据传输
msg.obj = "zhanglei";
//大量数据传输
Bundle b = new Bundle();
b.putInt("age",23);
b.putString("name", "zhanglei");
msg.setData(b);
//将msg发送到目标对象,所谓的目标对象就是生成该msg对象的Handler对象
msg.sendToTarget();
声明MyHandler类继承自Handler类:
class MyHandler extends Handler{
public MyHandler(){
}
public MyHandler(Looper looper){
super(looper);
}
//每当myHandler对象执行sendMessage方法时触发handleMessage方法
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
String str = (String)msg.obj; //将msg中的obj中的值取出
Bundle b = msg.getData();
int age = b.getInt("age");
String name = b.getString("name");
}
}