1、传入三个参数AsyncTask<Params,Progress,Result>
Params:启动任务时,输入参数的类型
Progress:后台任务执行中返回进度值的类型
Result:后台执行任务完成后返回结果的类型
2、四种方法:
1)doInBackground //执行耗时操作
2)onPreExecute //执行AsyncTask之前的操作
3)onProgressUpdate //控制ProgressBar等进度值的更新
4)onPostExecute //AsyncTask执行完成之后的操作
依次执行的顺序:onPreExecute、doInBackground、onProgressUpdate、onPostExecute
要执行onProgressUpdate方法,需要在doInBackground方法中执行publishProgress()
只有doInBackground异步加载,其他方法都是在主线程中执行,所以要在doInBackground中执行UI的更新等操作
3、线程取消:
例:
@Override
protected void onPause() {
super.onPause();
if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING){
mTask.cancel(true);
}
}
注:cancel只是将对应的AsyncTask标记为cancel状态,并不是真正的取消线程的执行
取消线程的执行2步:
1、在doInBackground判断是否标记为cancel状态
例:
//模拟进度更新
for (int i = 0; i < 100; i++) {
if (isCancelled()) {
break;
}
publishProgress(i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
2、在onProgressUpdate判断是否标记为cancel状态
例:
if (isCancelled()) {
return;
}
请多多指教!
关注我的技术公众号,每个工作日都有优质技术文章推送。
微信扫一扫下方二维码即可关注: