AsyncTask.onCancelled()不会被调用后取消(真) [英] AsyncTask.onCancelled() not being called after cancel(true)

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

问题描述

Android的SDK V15一2.3.6设备上运行。

Android SDK v15 running on a 2.3.6 device.

我在哪里 onPostExecute()当我打电话取消()依然被称为一个问题在 doInBackground()电话。

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

下面是我的code:

@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()返回值是真实的,所以我知道取消(真)正在执行。

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级别为3,而 onCancelled(对象结果)只因为API级11.因为这已被添加,如果平台API级别低于11, onCancelled()将被调用的总是的,而 onCancelled(对象)将被调用的总是的其他方式。

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上运行您的code以上,则需要实现这两种方法。为了拥有相同的行为,你可能想在一个实例变量存储结果,使 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);
  }
  private void handleCancelled(Boolean result) {
    // actual code here
  }
}

顺便说一句,Eric的code不容易的工作,因为Android的API文档说:

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

调用取消()方法将导致 onCancelled(对象) doInBackground(对象[])   回报。 调用cancel()方法保证    onPostExecute(对象)永远不会被调用。

Calling the cancel() method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling the cancel() method guarantees that onPostExecute(Object) is never invoked.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆