在我的Activity中,我使用了多个AsyncTask类。
如何在Activity完成时取消AsyncTask?
答案 0 :(得分:7)
我认为最好的地方是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
}
}
答案 1 :(得分:2)
答案 2 :(得分:2)
asynctask线程在线程池中保持活动状态,以用于AsyncTask的未来实例。你不能删除它们。