1、Handler的基本概念
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
Handler handler = new Handler();
handler.post(updateThread);//调用Handler的post方法,将要执行的线程对象条件到队列当中;
将要执行的操作写在线程对象的run方法中
Runable updateThread = new Runable();
{
public run(){
handler.postDelayed();
postDelayed(Runable r,long uptimeMillis)
Causes the Runnable to be added to the message queue ,to be run after the specified amount of time elapses.
}
}
Activity 处在一个线程中,自己的处理放在另一个线程中。
Handler updateBaHandler = new Handler(){
// Message : Defines a message containing a description and arbitrary data object that can be sent to a Handler.
// arg1 arg1 and arg2 are lower-cost alternatives to using setData() if you only need to store a few integer values.
public void handleMessage(Message msg){
bar.setProgress(msg.arg1);
updateBaHandler.post(updateThread);
}
};
//线程类,该类使用匿名内部类的方式进行生命
Runnable updateThread = new Runnable() {
int i = 0 ;
public void run() {
System.out.println("Begin Thread");
//得到一个消息对象,Message类是有Andoroid操作系统提供
i = i + 10;
Message msg = updateBaHandler.obtainMessage();//得到message对象
//将msg对象的arg1参数的值设置为i,用agr1和agr2系统优化
msg.arg1 = i;
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
updateBaHandler.sendMessage(msg);
if(i == 100){
updateBaHandler.removeCallbacks(updateThread);
}
//handler.postDelayed(updateThread, 3000);
}
};