package com.example.myasynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.widget.ProgressBar;
public class ProgressTest extends Activity{
private ProgressBar pb;
private MyAsynctask myAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_test);
pb = (ProgressBar) findViewById(R.id.pb);
myAsyncTask = new MyAsynctask();//asyncTask必须在UI线程中创建
myAsyncTask.execute();//必须在UI线程中调用execute()方法,而且中能调用一次,多次调用会引发异常
}
class MyAsynctask extends AsyncTask<Void, Integer, Void>{
@Override
protected Void doInBackground(Void... params) {
for(int i = 0 ; i < 100 ; i++){
if(isCancelled()){
return null;
}
SystemClock.sleep(500);
publishProgress(i);//当调用此方法时,系统才会调用onProgressUpdate方法,参数即是onProgressUpdate的参数
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(isCancelled()){
return;
}
Log.i("TAG",""+values[0]);
pb.setProgress(values[0]);
}
}
@Override
protected void onPause() {
super.onPause();
//当activity不可见时将asyncTask标记为取消状态
if(myAsyncTask != null && myAsyncTask.getStatus() == MyAsynctask.Status.RUNNING){
myAsyncTask.cancel(true);
}
}
}
AsynckTask的简单使用(更新进度条)
最新推荐文章于 2018-10-16 20:22:28 发布