问题
I have an Asynctask B that is executed from activity A. On post execute of that B, on a certain condition B might create a new instance of itself and execute it.
What i did is put the AsyncTask declaration as global inside the B and overridden the onCancelled of B to cancel the new instance that is created onpostexecute.
so onDestroy of Activity A b.cancel() will also cancel the any AsyncTask executed onPostExecute.
@Override
protected void onCancelled()
{
if(currentPlansAsync != null)
{
currentPlansAsync.cancel(true);
}
super.onCancelled();
}
And new instance of currentPlansAsync is called onPostExecute as follows:
private void processAfterFailure()
{
if(this.counter < 3)
{
ProgressDialog progressDialog =
GeneralUtils.showProgressDialog(parentActivity, parentActivity.getResources().getString(string.WaitDialogTitle),
parentActivity.getResources().getString(string.WaitDialogMessage));
this.counter++;
currentPlansAsync = new CurrentPlansAsync(parentActivity, application, progressDialog, application.planBL, this.counter);
currentPlansAsync.execute();
}
else
{
Toast.makeText(parentActivity, parentActivity.getResources().getString(string.SERVICE_ERROR), Toast.LENGTH_LONG).show();
}
}
My question is that if AsyncTask B has stopped execution and it has executed another asynctask C and activity A goes to onDestroy and B is cancelled ( b.cancel(true);)
will onCancelled that is overridden in class B be called ??
This is so i ensure that i cancel the AsyncTask that was executed from the activity and also the AsyncTask executed from within that AsyncTask
回答1:
onCancelled() is called immediately after the doInBackground() returns, if a cancel() call has been made before the background job has finished.
It will not be called if you cancel() the AsyncTask after that.
I would recommend to create a public method that will do what will cancel all child tasks, and call this public method:
public void cancelChildTasks()
{
if(currentPlansAsync != null)
{
currentPlansAsync.cancel(true);
currentPlansAsync.cancelChildTasks();
}
}
You should still call and handle the cancel() method of the AsyncTasks in order to stop the doInBackground() execution if it is in the middle of execution. Just deal with the child tasks in the public methods instead of in the onCancelled().
来源:https://stackoverflow.com/questions/16302769/canceling-asynctask-that-is-not-running-calls-oncancelled