onPreExecute doInBackground publishProgress onProgressUpdate onPostExecute
一定得记得调用execute开启任务
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
//主线程
Toast.makeText(Class2MainActivity.this, "扫描中", 0).show();
showAnimation();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//子线程
//更新进度
int count = 100;
pb.setMax(count);
for(int i=0;i<count;i++){
SystemClock.sleep(50);
publishProgress();
}
return null;
}
@Override
// publishProgress会调用下面的方法 在主线程了
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
//增加
pb.incrementProgressBy(1);
super.onProgressUpdate(values);
}
//回到了主线程
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//停止动画
iv.clearAnimation();
Toast.makeText(Class2MainActivity.this, "扫描结束", 0).show();
super.onPostExecute(result);
}
}.execute();