布局代码很简单就是一个progressBar和一个Button
代码略:
Java代码如下:
public class MainActivity extends Activity {
ProgressBar pb;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb=(ProgressBar) findViewById(R.id.pb);
button=(Button) findViewById(R.id.button);
button.setOnClickListener(new startButton());
}
class startButton implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//设置pragressBar为可见状态
pb.setVisibility(View.VISIBLE);
handler.post(updateThread);
}
}
//
Handler handler=new Handler(){
public void handleMessage(Message msg){
pb.setProgress(msg.arg1);
handler.post(updateThread);
}
};
//线程类;
Runnable updateThread=new Runnable(){
int i=0;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("beigin i"+i);
i=i+10;
//得到一个消息对象,Message类是有Android操作系统提供
Message msg=handler.obtainMessage();
//用arg1和arg2传递消息,优点是
msg.arg1=i;
Bundle bundle=new Bundle();
bundle.putString("test","test bundle");
try {
//设置当前线程睡眠
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(msg);
//将msg对象加入到消息队列当中
if(i==100){
//如果i的值为100时,将线程对象chonghandler队列中移除
handler.removeCallbacks(updateThread);
}
}
};
}
实现了异步功能;