Android – Cancel AsyncTask in Android

By -

I assume you have already used AsyncTask, If you haven’t used or know about it then read my article on What is AsyncTask or visit read official documentation on AsyncTask.

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

Now the question is How to Cancel(or stop execution) the running AsyncTask execution? From the documentation, you find a paragraph on “Cancelling a Task“:

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 as per the above description, we need to 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.

asyncTask.cancel(true);

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

protected Object doInBackground(Object... x)  { 

   while (/* condition */)
   {
      ...
      if (isCancelled())  
         break;
   } 
   return null; 
}

FYI, I faced this problem and I had asked a 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

Loading Facebook Comments ...
Loading Disqus Comments ...