gpt4 book ai didi

android - 如何在 Activity 完成时取消 AsyncTask?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:40 24 4
gpt4 key购买 nike

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

然后在我的任务中,我会尽可能频繁地检查是否调用了cancel

protected String doInBackground(String... arg0) {
if (this.isCancelled()) {
return null;
}
}

当然不要忘记丢弃可能返回的数据,因为没有更多的 Activity 可以接收它

protected void onPostExecute(List<UserStatus> result) {
if(!this.isCancelled()) {
//pass data to receiver
}
}

关于android - 如何在 Activity 完成时取消 AsyncTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com