不完整的异步任务导致活动崩溃

时间:2014-01-22 18:43:07

标签: android android-fragments android-asynctask

我在我的一个片段中使用了asynctask。但是在完成asynctask之前按回来应用程序崩溃了。我在片段的onstart方法中调用asynctask。

这是我正在执行asynctask的片段onStart方法。

public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    new FetchTableTask().execute();

}

我应该在代码中添加什么,这样即使asynctask不完整,app也不会崩溃。

1 个答案:

答案 0 :(得分:0)

按下后退时,可能会在异步任务上调用cancel,然后在代码中添加条件以检查它是否已被取消,因此它不会执行导致崩溃的任何操作。

以下是documentation中的示例,请注意isCancelled()调用。

 protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
相关问题