在我的活动中,我使用了多个 AsyncTask 类。
Activity 完成时如何取消 AsyncTask?
在我的活动中,我使用了多个 AsyncTask 类。
Activity 完成时如何取消 AsyncTask?
我认为最好的地方是onStop
protected void onStop() {
super.onStop();
/*
* The device may have been rotated and the activity is going to be destroyed
* you always should be prepared to cancel your AsnycTasks before the Activity
* which created them is going to be destroyed.
* And dont rely on mayInteruptIfRunning
*/
if (this.loaderTask != null) {
this.loaderTask.cancel(false);
}
}
然后在我的任务中,我尽可能经常检查是否调用了取消
protected String doInBackground(String... arg0) {
if (this.isCancelled()) {
return null;
}
}
当然不要忘记删除可能返回的数据,因为没有更多的活动来接收它
protected void onPostExecute(List<UserStatus> result) {
if(!this.isCancelled()) {
//pass data to receiver
}
}
asynctask 线程在线程池中保持活动状态,以供将来的 AsyncTask 使用。你不能删除它们。