1.
//使用匿名内部类来复写Handler当中的handleMessage方法
Handler updateBarHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
bar.setProgress(msg.arg1);
updateBarHandler.post(updateThread);
}
};
//线程类,该类使用匿名内部类的方式进行声明
Runnable updateThread = new Runnable(){
int i = 0 ;
@Override
public void run() {
System.out.println("Begin Thread");
i = i + 10 ;
//得到一个消息对象,Message类是有Android操作系统提供
Message msg = updateBarHandler.obtainMessage();
//将msg对象的arg1参数的值设置为i,用arg1和arg2这两个成员变量传递消息,优点是系统性能消耗较少
msg.arg1 = i ;
try {
//设置当前显示睡眠1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将msg对象加入到消息队列当中
updateBarHandler.sendMessage(msg);
if( i == 100){
//如果当i的值为100时,就将线程对象从handler当中移除
updateBarHandler.removeCallbacks(updateThread);
}
}
};
2.
onCreate
//生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能,这个类由Android应用程序框架提供
HandlerThread handlerThread = new HandlerThread("handler_thread");
//在使用HandlerThread的getLooper()方法之前,必须先调用该类的start();
handlerThread.start();
MyHandler myHandler = new MyHandler(handlerThread.getLooper());
Message msg = myHandler.obtainMessage();
//将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象
Bundle b = new Bundle();
b.putInt("age", 20);
b.putString("name", "Jhon");
msg.setData(b);
msg.sendToTarget();
class MyHandler extends Handler{
public MyHandler(){
}
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
int age = b.getInt("age");
String name = b.getString("name");
System.out.println("age is " + age + ", name is" + name);
System.out.println("Handler--->" + Thread.currentThread().getId());
System.out.println("handlerMessage");
}
}