在我的 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);
    }
}

在我的任务i,那么检查尽可能经常如果取消被称为

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的未来实例线程池保持存活。你不能删除它们。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top