4

在我的活动中,我使用了多个 AsyncTask 类。

Activity 完成时如何取消 AsyncTask?

4

3 回答 3

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
    }
}
于 2012-12-13T11:40:48.333 回答
2

我不明白您的“取消”是否意味着回滚,但您在AsyncTask类上有一个取消方法。

于 2010-03-28T14:26:12.743 回答
2

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

于 2011-10-17T08:12:00.533 回答