Android - Cancel AsyncTask Forcefully

Paresh Mayani picture Paresh Mayani · Jan 20, 2011 · Viewed 93k times · Source

I have implemented AsyncTask in my one of activity:

 performBackgroundTask asyncTask = new performBackgroundTask();
 asyncTask.execute();

Now, i need to implement the "Cancel" button functionality, so i have to stop the execution of the running task. I don't know how do i stop the running task(background task).

So Please suggest me, how do i cancel the AsyncTask forcefully ?

Update:

I found about the Cancel() method of the same, but i found that calling cancel(boolean mayInterruptIfRunning) doesn't necessarily stop the execution of the background process. All that seems to happen is that the AsyncTask will execute onCancelled(), and won't run onPostExecute() when it completes.

Answer

Jacob Nordfalk picture Jacob Nordfalk · Jan 22, 2011

Just check isCancelled() once in a while:

 protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }