Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Cancel AsyncTask Forcefully

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.

like image 879
Paresh Mayani Avatar asked Jan 20 '11 15:01

Paresh Mayani


People also ask

How to stop running AsyncTask in Android?

AsynTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask. cancel(true);

How do I stop AsyncTask when activity is destroyed?

You can either cancel the AsyncTask in the onStop method of your activity or you can let your async task finish, and not loose its progress and relink it to the next instance of your activity.


1 Answers

Just check isCancelled() once in a while:

 protected Object doInBackground(Object... x) {     while (/* condition */) {       // work...       if (isCancelled()) break;     }     return null;  } 
like image 182
Jacob Nordfalk Avatar answered Oct 17 '22 08:10

Jacob Nordfalk