在我的 Activity 中,我使用了多个 AsyncTask 类。
如何在 Activity 结束时取消 AsyncTask?
在我的 Activity 中,我使用了多个 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实例可以使用。您无法删除它们。