Thanks to the publication of the companion @Michel_Escalante_Alvarez I have adapted its code to what I have been found by SO.
Creating cancelable ProgressDialog '
To create a ProgressDialog
that can be canceled by pressing the physical / virtual button at the back, but avoiding that if it is pressed outside the dialog it will not close.
progress.setCancelable(true);
progress.setCanceledOnTouchOutside(false);
and when canceling the dialogue it is intercepted with
progress.setOnCancelListener(...)
To cancel the asyncTask
cancel(false);
Entire code of the creation of the dialogue:
@Override
protected void onPreExecute() {
super.onPreExecute();
//Show dialog bar
progress = new ProgressDialog(MainActivity.this);
progress.setTitle("titulo");
progress.setMessage("progreso x");
progress.setCancelable(true);
progress.setCanceledOnTouchOutside(false);
progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
cancel(false); //se cancela el asyntask
}
});
progress.show();
}
Driver when canceling the task
In the event doInBackground
with the function isCancelled
can be obtained if you need to cancel.
@Override
protected Boolean doInBackground(Void... voids) {
if (!isCancelled()) {
//seguir la tarea
} return false;
return true;
}
Completely complete the task
When the task is finished correctly or has been canceled, the event onPostExecute
is computed
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
progress.dismiss();
Log.i(TAG, "onPostExecute: Finalizado correctamente" );
} else {
Log.w(TAG, "onPostExecute: Cancelación por parte del usuario");
}
}
Capture the cancellation
You can intercept the event before canceling with onCancelled
@Override
protected void onCancelled(Boolean aBoolean) {
super.onCancelled(aBoolean);
Log.w(TAG, "onCancelled: " + aBoolean );
}