AsyncTask.onCancelled () is not called after cancellation (true)

Android SDK v15 runs on device 2.3.6.

I am having a problem when onPostExecute() is still being called when I call cancel() in the doInBackground() call.

Here is my code:

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

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

Any ideas?

+6
android android-asynctask
Jun 23 2018-12-12T00:
source share
2 answers

According to the Android API document, onCancelled() exists from API level 3, and onCancelled(Object result) was added only from API level 11. In this regard, if the platform API level is below 11, onCancelled() will always be called, and onCancelled(Object) will always be called differently.

So, if you want to run your code at all levels of API 3 and above, you need to implement both methods. To have the same behavior, you might 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 code is unlikely to work, because the Android API document says:

Calling the cancel() method will result in a call to onCancelled(Object) in the user interface thread after doInBackground(Object[]) returned. Calling the cancel () method ensures that onPostExecute(Object) never called.

+21
Dec 13
source share

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

It is best 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 version checking, you can do the following:

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

Hope this helps! :)

+6
Jun 23 '12 at 1:17
source share



All Articles