Is there anyway to cancel all the running instances of an Asynctask ? Thanks in advance.
I want to cancel the progress dialog on pressing back button meanwhile all the instances of an asynctask from the same piece of code.
Is there anyway to cancel all the running instances of an Asynctask ? Thanks in advance.
I want to cancel the progress dialog on pressing back button meanwhile all the instances of an asynctask from the same piece of code.
You can't cancel all instances WITHOUT a reference to EACH individual AsyncTask.
Read docs on what cancel() does form AsyncTask.
Once you have a reference to each AsyncTask, then you can cancel each of them.
use following code to cancel running asynctask
if(myAsyncTask.getStatus().equals(AsyncTask.Status.RUNNING))
{
myAsyncTask.cancel(true);
}
I could solve it making a flag in OnStop()
1- Declare a global
int flagOnStop=0;
2- Declare all global AsyncTask -->
Async_Task asyncTask1,asyncTask2,asyncTaskn;
3- Before execute it, ask for flagOnStop -->
if(flagOnStop==0{
asyncTask1=new Async_Task();
asyncTask1.execute();
asyncTask2=new Async_Task();
asyncTask2.execute();
asyncTaskn=new Async_Task();
asyncTaskn.execute();
}
4- When your activity stop make the flag equals to one
@Override
public void onStop() {
super.onStop();
flagOnStop=1;
asyncTask.cancel();
asyncTask2.cancel();
asyncTaskn.cancel();
}
Set a boolean flag in your activity (or wherever visible to the asynctasks) and inside the asynctask do:
while (flag) {
your_logic;
}
When pressing back set the flag to false and every asynctask should stop itself - then you don't need a reference to the asyntasks themselves because they will do all the work.
FOUND THE SOLUTION: I added an action listener before uploadingDialog.show() like this:
uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
myTask.cancel(true);
//finish();
}
});
That way when I press the back button, the above OnCancelListener cancels both dialog and task. Also you can add finish() if you want to finish the whole activity on back pressed. Remember to declare your async task as a variable like this:
MyAsyncTask myTask=null;
and execute your async task like this:
myTask = new MyAsyncTask();
myTask.execute();
Reference : Android: Cancel Async Task