I am using AsyncTask
in my Android application.
Here is my task:
public class MyTask extends AsyncTask<String, String, Boolean> {
private ProgressDialog progressDialog;
private boolean isCancelled = false;
public MyTask(ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
@Override
protected Boolean doInBackground(String... params) {
try {
if (!isCancelled()) {
isCancelled = false;
} else
isCancelled = true;
} catch (Exception e) {
isCancelled = true;
}
return isCancelled;
}
@Override
protected void onCancelled() {
super.onCancelled();
isCancelled = true;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressDialog.dismiss();
if (!isCancelled) {
// start an activity
}
}
}
I want to cancel this task when pressing device's back button and also cancel the ProgressDialog
, but this task executes quickly. When the back button is pressed, the ProgressDialog
is cancelled, but the task completes.
This AsyncTask
is invoked from an activity like this:
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (myTask!= null
&& myTask.getStatus() != AsyncTask.Status.FINISHED
&& !myTask.isCancelled()) {
myTask.cancel(true);
}
}
});
progressDialog.show();
myTask = new MyTask(progressDialog);
myTask.execute();
When logging, I found that the dialog is dismissed (invokes onDismissListener
) after executing the condition of onPostExecute()
. How can I cancel this task properly?
My intention is cancel the task with back button press whether the task completes or not. Is it possible to cancel an AsyncTask from its onPostExecute()
?