I am learning how to cancel asyncTask so there is no uses on the code below.
I tried to called the asyncTask and execute it then cancel it and execute it.
You can use either
asynctask.cancel(true);
or
asyncTask.wait();
"true " if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete
My approach is slightly different and perhaps, a little lengthy. But it has always worked without any issues.
This piece of code goes in the doInBackground()
. If you have a for... loop
in it, then use the break;
statement. If you do not use a for.... loop
, remove it.
// CHECK IF THE USER HAS CANCELLED THE TASK
if (isCancelled()) {
cancelTask = true; // (OPTIONAL) THIS IS AN ADDITIONAL CHECK I HAVE USED. THINK OF IT AS A FAIL SAFE.
break; // REMOVE IF NOT USED IN A FOR LOOP
}
You already have an Asynctask
declared: MyAsyncTask asyncTask = new MyAsyncTask();
. Along with that, also create two instances of boolean
. Call them, for example:
boolean blMyAsyncTask;
boolean cancelTask;
Now, in the onPreExecute()
, toggle the status of the blMyAsyncTask instance:
blMyAsyncTask = true;
And in the onPostExecute()
:
blMyAsyncTask = false;
And, in the same onPostExecute()
, I also do the remainder functions after checking the state of the cancelTask boolean
. For example:
if (cancelTask == false) {
// THE NORMAL CODE YOU HAVE IN YOUR onPostExecute()
}
Finally, in the onDestroy()
(I use this, but I suspect the onPause()
could work too. Never done it in the onPause()
in all honesty), check the status of the boolean blMyAsyncTask
if (blMyAsyncTask== true) {
asyncTask.cancel(true);
}
As I said at the start, it is lengthy, perhaps even complicated, but it has never failed. I also think of this as a little modular if you would. If I have more Asycntasks
added to the Activity
, I can add another check in the onDestroy()
.
you should not call asyncTask.onCancelled();
directly. You can call cancel(true)
and inside your doInBackground()
you check for isCancelled()
.
To cancel a AsyncTask call the below line.
asyncTask.cancel();
onCancelled() is a override method that is executed when ever cancel is called.