在我的应用程序中,我有一个 AsyncTask,我还创建了一个列表,用于将任务添加到该列表。
在 AsyncTask 中,我正在下载一些信息,它工作得很好,但是,当使用 finish() 关闭 Activity 时,我经常会强制关闭,因为 AsyncTask 没有关闭并且当它到达 onPostExecute 并想要与 UI 交互时,它崩溃导致 Activity 被破坏!
这是我试过但没用的方法:
for (int i = 0; i<tasks.size(); i++){
tasks.get(i).cancel(true);
}
finish();
那么有没有办法强制停止 AsyncTasks 呢?
您对 asyncTask.cancel(true)
感兴趣,实际上在其参数中传递 true,如文档中所示:
mayInterruptIfRunning true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
然后在你的 AsyncTask.doInBackground 中,你可以像下面这样尝试/捕获 - 但这需要你有抛出 InterruptedException 的阻塞调用,否则你需要不时检查 isCancelled():
@Override
protected Void doInBackground(Void... params) {
try {
/// do work,
} catch (InterruptedException e) {
if ( isCancelled() ) {
// cancel(true) called, dont touch UI!
}
}
return null;
}
此外,在 onPostExecute()
的开头检查 isCancelled() 是安全的.
when it reaches to onPostExecute and wants to interact with UI, it crashes
那是另一个问题,如果你在里面互动 AsyncTask
使用 GUI,我首先建议:要使 AsyncTask 成为静态类,将对 Activity 或 Fragment 的引用传递给 AsyncTask 构造函数,然后将其存储为 WeakReference<MyActivity> actRef
.然后当你需要它时使用 if ( actRef.get() != null ) {//使用它。 }.通过这种方式,您希望泄漏对您的 Activity/fragment 的引用或使用无效的 UI 对象。