下载进度条案例,用于体会异步任务
private Button btn01;
private ProgressBar pBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn01=(Button) findViewById(R.id.button1);
pBar=(ProgressBar) findViewById(R.id.progressBar1);
}
private int currentPos;//用于记录进度当前位置
private DownTask dTask;
public void onClick01(View v){
//1.构建异步任务对象
dTask=new DownTask(currentPos);
//2.启动执行异步任务(execute方法中的参数会传递给doInbackground)
dTask.execute("task-01");
}
public void onClick02(View v){
dTask.cancel(true);//尝试停止正在执行的任务,false是登任务执行完再停止
//此时isCancel方法返回值为true
}
class DownTask extends AsyncTask<String,Integer,CharSequence>{
private int pos;
public DownTask(int pos) {
this.pos=pos;
}
/**此方法运行在主线程,在doinbackground方法之前执行*/
@Override
protected void onPreExecute() {
Log.i("TAG","onPreExecute");
pBar.setVisibility(View.VISIBLE);
pBar.setMax(10);
}
/**运行在工作线程*/
@Override
protected CharSequence doInBackground(String... params) {
Log.i("TAG",params[0]+"开始执行");
//try{Thread.sleep(5000);}catch(Exception e){}
for(int i=pos;i<=10;i++){
try{Thread.sleep(1000);}catch(Exception e){}
if(isCancelled()){//判定任务是否要退出
pos=i;//记录当前进度条进度
break;
}else{
publishProgress(i);//发布进度,此值会传递给onProgressUpdate
}
}
Log.i("TAG",params[0]+"任务执行结束");
return params[0];
}
/**此方法运行于主线程,用于更新进度,只有publishProgress方法
* 执行以后此方法才会执行*/
@Override
protected void onProgressUpdate(Integer... values) {
pBar.setProgress(values[0]);
}
/**此方法运行在主线程,在doInbackGround方法执行结束以后
* 执行,且doInbackground方法的返回值会以参数的形式传递
* 给此方法,通常会在此方法中执行UI更新操作*/
@Override
protected void onPostExecute(CharSequence result) {
btn01.setText(result+"执行结束");
pBar.setVisibility(View.GONE);
}
@Override
protected void onCancelled() {
Log.i("TAG", "onCancelled");
currentPos=pos;//停止时的进度位置赋值给当前进度位置
Log.i("TAG", "currentPos="+currentPos);
}
}