Android – Cancel AsyncTask in Android

By -



I assume you are knowing about AsyncTask, If you are not knowing about AsyncTask then please visit my article on What is AsyncTask or visit this link once: http://developer.android.com/reference/android/os/AsyncTask.html.

Now while using AsyncTask , many times you might have faced a situation where you want to stop the AsyncTask process by clicking Back key or clicking on Cancel button or any way you want to stop the AsyncTask process.

Now the question is How to Cancel(or stop execution) the running AsyncTask execution? From above SDK link, you may find a paragraph on “Cancelling a Task“, here it is:

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)


so implement two things to stop the AsyncTask execution:

1. call Cancel() method of AsyncTask from where you want to stop the execution, may be based on the button click.

For example:


 asyncTask.cancel(true);

2. Now you have to check whether the AsyncTask is cancelled or not by using isCancelled method inside the doInBackground method.

For example:


protected Object doInBackground(Object... x) { while (/* condition */)

{

// work...

if (isCancelled())  break;

} return null; }

FYI, I have faced the same problem to cancel to AsyncTask forcefully, here is my question on StackOverflow: http://stackoverflow.com/questions/4748964/android-cancel-asynctask-forcefully, many thanks to jn0101 and CommonsWare for providing answer on the question.


 
 
 

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

  • http://in.linkedin.com/in/vikaskanani Vikas

    Great, can we cancel from UI?

    • http://pareshnmayani.wordpress.com Paresh N Mayani

      I didnt get your meanning, but while AsyncTask is running in background and if you want to cancel it by clicking on “cancel” or “back” from your layout then you can.

      • Sahana Udaya

        Hi,
        I want to cancel the AsyncTask on pressing “Back” button on Android. How can we do this?

        If the AsyncTask doesn’t receive any response from server. Then on initiating the call again it throws the below error:
        java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
        at android.os.AsyncTask.execute(AsyncTask.java:383)……………

  • http://pareshnmayani.wordpress.com Paresh N Mayani

    To implement “Back” button functionality, i assume you are talking about “Back” key, so to implement “Back” key functionality write the below code, and also include cancel() method inside the same method.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    // do something on back.
    return true;
    }

    return super.onKeyDown(keyCode, event);
    }

    or as of 2.0 you can also implement:

    @Override
    public void onBackPressed() {
    // do something on back.
    return;
    }

  • http://vikaskanani.wordpress.com Vikas

    Okay, Thanks for pointing out. This just strike me to do some research work. Then it was required when I was doing bug fixing.

    My flavor of explaining this case is here

    • http://pareshnmayani.wordpress.com Paresh N Mayani

      Hello vikas,
      Thanx for the refinement on article. But you know your code looks lengthy , nobody can understand the code while reading.

      Anyway, Nice article.

  • http://vikaskanani.wordpress.com Vikas

    Yep, you are correct, But when it comes to “proper” word, I need to take care of logical aspect. and to explain that, so I used login activity. cheers with Android.

  • Shahzad Imam

    @Paresh: On my activity i am showing phonebook sync button .when it is clicked,sync button is gone and a progress bar with cancel button is visible on screen.Now i am confused, where should i use this cancel button in my activity.I am not using any dialog.