I have an AsyncTask that shows a progressDialog whilst working (it calls runOnUiThread from within doInBackground to show the progress dialog).
<
I just found a perfect and simplest solution to this problem. There's a method in ProgressDialog
to set KeyListener.
progressDialog.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && !event.isCanceled()) {
if(progressDialog.isShowing()) {
//your logic here for back button pressed event
}
return true;
}
return false;
}
});
It's working fine with setCancelable(false)
. I am also checking for event.isCanceled()
, because without that I was getting two events. I've tested this on Lollipop device with and without Hardware keys.