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.


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())  
   return null; 

FYI, I faced this problem and I had asked a question on StackOverflow:, many thanks to jn0101 and CommonsWare for providing answer on the question.

Paresh Mayani

Lazy android developer, exploring the horizon of android development since 7 years, currently working as a Technical Lead - Android at Simform Solutions, India. Former Application Architect at KarConnect. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

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