AsyncTask.onCancelled() not being called after cancel(true)

后端 未结 2 1036
难免孤独
难免孤独 2020-12-03 22:38

Android SDK v15 running on a 2.3.6 device.

I\'m having an issue where onPostExecute() is still being called when I am calling cancel() with

相关标签:
2条回答
  • 2020-12-03 23:07

    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.

    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
      }
    }
    

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

    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.

    0 讨论(0)
  • 2020-12-03 23:11

    onCancelled is only supported since Android API level 11 (Honeycomb 3.0.x). This means, on an Android 2.3.6 device, it will not be called.

    Your best bet is to have this in onPostExecute:

    protected void onPostExecute(...) {
        if (isCancelled() && Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            onCancelled();
        } else {
            // Your normal onPostExecute code
        }
    }
    

    If you want to avoid the version check, you can instead do:

    protected void onPostExecute(...) {
        if (isCancelled()) {
            customCancelMethod();
        } else {
            // Your normal onPostExecute code
        }
    }
    protected void onCancelled() {
        customCancelMethod();
    }
    protected void customCancelMethod() {
        // Your cancel code
    }
    

    Hope that helps! :)

    0 讨论(0)
提交回复
热议问题