本文介绍了AsyncTask.onCancelled() 在取消后没有被调用(真)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 2.3.6 设备上运行的 Android SDK v15.

Android SDK v15 running on a 2.3.6 device.

我遇到了一个问题,当我在 doInBackground() 中调用 cancel() 时,仍然会调用 onPostExecute()打电话.

I'm having an issue where onPostExecute() is still being called when I am calling cancel() within a doInBackground() call.

这是我的代码:

@Override
public String doInBackground(String... params) {
    try {
        return someMethod();
    } catch (Exception e) {
        cancel(true);
    }

    return null;
}

public String someMethod() throws Exception {
    ...
}

我强制 someMethod() 抛出一个异常来测试这个,而不是调用 onCancelled,我总是返回到 onPostExecute().如果我检查 isCancelled() 返回的值为 true,所以我知道 cancel(true) 正在执行.

I am forcing someMethod() to throw an exception to test this out, and instead of onCancelled being called, I always return to onPostExecute(). If I check isCancelled() the returned value is true, so I know that cancel(true) is being executed.

有什么想法吗?

推荐答案

根据 Android API 文档,onCancelled() 从 API level 3 开始就有,而 onCancelled(Object result) 仅从 API 级别 11 开始添加.因此,如果平台 API 级别低于 11,则 onCancelled() 将被调用 alwaysonCancelled(Object) 将被调用总是否则.

According to the Android API document, onCancelled() is there since API level 3, while onCancelled(Object result) had been added only since API level 11. Because of that, if the platform API level is below 11, onCancelled() will be invoked always while onCancelled(Object) will be invoked always otherwise.

因此,如果您想在所有 API 级别 3 及更高级别上运行您的代码,则需要实现这两种方法.为了具有相同的行为,您可能希望将结果存储在实例变量中,以便可以使用 isCancelled() ,如下所示:

So, if you want to run your code on all API level 3 and above, you need to implement both methods. In order to have the same behavior you may want to store the result in an instance variable so that isCancelled() can be used as shown below:

public class MyTask extends AsyncTask<String, String, Boolean> {
  private Boolean result;
  // . . .
  @Override
  protected void onCancelled() {
    handleOnCancelled(this.result);
  }
  @Override
  protected void onCancelled(Boolean result) {
    handleOnCancelled(result);
  }
  //Both the functions will call this function
  private void handleOnCancelled(Boolean result) {
    // actual code here
  }
}

顺便说一下,Eric 的代码不太可能工作,因为 Android API 文档说:

By the way, Eric's code does not likely work because the Android API doc says:

调用cancel()方法会导致onCancelled(Object)doInBackground(Object[])之后在UI线程上被调用返回.调用cancel()方法保证onPostExecute(Object) 永远不会被调用.

这篇关于AsyncTask.onCancelled() 在取消后没有被调用(真)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 00:48