gpt4 book ai didi

android - 如何在取消 Activity 时退出所有异步任务?

转载 作者:行者123 更新时间:2023-11-29 01:33:03 26 4
gpt4 key购买 nike

根据下面的帖子: http://techtej.blogspot.com.es/2011/03/android-thread-constructspart-4.html .它说:

In such cases, where your application is not shutdown, but any foreground tasks have been closed or changed, all the background tasks need to know of this and try to exit gracefully

为此,我在所有 AsyncTask 实例上调用了 cancel 函数。这是正确的方法吗?有时在图像延迟加载中,我不会跟踪所有 Activity 的 AsyncTask(和获取图像),所以如何说 Android OS 也取消它们?

最佳答案

您可以通过检查线程(AsyncTask) 对象的状态来取消AsyncTask

private Example ex = new Example();

class Example AsyncTask<Object, Void, Void> {
@Override
protected Void doInBackground(Object... params) {
String result = null;
if(!isCancelled())
result = getHttpRestManager().send();
if(!isCancelled()) {
// some codes
}
...
return null;
}
}

public boolean cancel() {
switch(ex.getStatus()) {
case RUNNING:
case PENDING:
return ex.cancel(true);
case FINISHED:
return false;
}
return false;
}



取消线程后,它的状态总是返回 RUNNINGFINISHED。如果状态不是PENDING,则不能执行线程。所以你必须在每次 .execute() 之前初始化新的线程对象,比如 ex = new Example()

关于android - 如何在取消 Activity 时退出所有异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30188251/

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