4

在我的活动中,我使用了多个AsyncTask类。如何在活动结束时取消AsyncTask?

如何在Activity结束时取消AsyncTask?

+1

请参阅http://stackoverflow.com/questions/2531336/asynctask-wont-stop-even-when-the-activity-has-destroyed – CommonsWare 2010-03-28 14:26:24

+0

检查此正确的方法来取消一个asynctask http:// www.quicktips.in/correct-way-to-cancel-an-asynctask-in-android/ – 2016-06-29 17:09:11

回答

2

我不明白你的“取消”是否意味着回滚,但你有AsyncTask类的cancel方法。

+0

任务完成后,我希望它消失。 – Pentium10 2010-03-28 14:35:18

2

asynctask线程在线程池中保持活动状态,以用于未来的AsyncTask。你不能删除它们。

+0

虽然这可能是真的,但问题是关于取消任务,而不是摆脱它的线程。 – 2011-10-17 11:27:41

+0

注意@Pentium10在接受的答案中发表评论 - 他希望“任务”(我相信意思是“线程”)“消失”这就是为什么我认为这个答案是最好的 – condiosluzverde 2012-04-25 22:27:04

+0

谢谢詹姆斯:) – 2012-04-26 07:01:48

6

我认为要做到这一点,最好的地方是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

onPostExecute永远不会被调用isCancelled设置为true,而是调用onCancelled(Object) – 2014-02-14 07:08:17