Android Back Button and Progress Dialog

前端 未结 9 2066
攒了一身酷
攒了一身酷 2021-01-31 03:24

I have an AsyncTask that shows a progressDialog whilst working (it calls runOnUiThread from within doInBackground to show the progress dialog).

<
9条回答
  •  梦谈多话
    2021-01-31 03:51

    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.

提交回复
热议问题