Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android-How to close progress dialog when back button is pressed

Tags:

android

How to close progress dialog when back button is pressed ?

like image 918
Dev Avatar asked Sep 16 '11 14:09

Dev


2 Answers

By default progress dialog get dismiss, if you click on back button. Or, you can add this line:

progress.setCancelable(true);

Another option is you can call finish() and then progress.dismiss():

progress.setOnKeyListener(new ProgressDialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface arg0, int keyCode,
                KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                finish();
                dialog.dismiss();
            }
            return true;
        }
});

Or, you override method onCancel() method in back key pressed button event.

like image 73
Divya Avatar answered Oct 20 '22 11:10

Divya


A much better way.

          ProgressDialog dialog = new ProgressDialog(this);
          dialog.setCancelable(true);
          dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
             @Override
             public void onCancel(DialogInterface dialog){
                /****cleanup code****/
          }});           

The setCancelable method tells the ProgressDialog to close when the back button is pressed. The listener at the end allows you to do anything that may need to be done as a result of a cancel (like closing a socket).

like image 41
DeeV Avatar answered Oct 20 '22 10:10

DeeV