【问题标题】:incomplete async task crashes the activity不完整的异步任务使活动崩溃
【发布时间】:2014-01-22 18:43:06
【问题描述】:

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

这是我正在执行异步任务的片段的 onStart 方法。

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

}

我应该在代码中添加什么,这样即使异步任务不完整,应用程序也不会崩溃。

【问题讨论】:

标签: android android-fragments android-asynctask


【解决方案1】:

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

这是来自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;
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多