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

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