我有一个主Activity请求另一个类的信息,该类从Web服务获取该信息,因此我在AsyncTask类上执行此操作。在数据加载时,主Activity显示一个ProgressDialog,我处理返回按钮,以便在按下时可以解除对话框,但现在我想取消AsyncTask。我创建了一个静态布尔变量,当按下返回按钮时为“true”,因此从AsyncTask的doInBackground方法中检查该变量是否为true,如果是,则取消AsyncTask:
@Override protected Void doInBackground(Integer... args) {
try {
....
if ( MainActivity.isDialogCancelled ){
cancel(true);
}
....
} catch (Exception e) {
....
}
}
这似乎工作得很好,但是当我通过这种方式取消任务时,我看到一个 InterruptedException 警告,为什么会发生这种情况,并且我如何避免它们?我做错了什么吗?
这些是警告:
01-24 18:40:50.582: W/AsyncTask(22877): java.lang.InterruptedException
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1272)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:220)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.FutureTask.get(FutureTask.java:83)
01-24 18:40:50.582: W/AsyncTask(22877): at android.os.AsyncTask$3.done(AsyncTask.java:196)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.FutureTask$Sync.innerCancel(FutureTask.java:294)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.FutureTask.cancel(FutureTask.java:76)
01-24 18:40:50.582: W/AsyncTask(22877): at android.os.AsyncTask.cancel(AsyncTask.java:325)
01-24 18:40:50.582: W/AsyncTask(22877): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-24 18:40:50.582: W/AsyncTask(22877): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-24 18:40:50.582: W/AsyncTask(22877): at java.lang.Thread.run(Thread.java:1019)
提前感谢您。