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

后端 未结 2 1050
难免孤独
难免孤独 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: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! :)

提交回复
热议问题