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.

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

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