简体   繁体   中英

dismissing Progress Dialog

I have a situation where I am loading a bunch of images. During this process, I am trying to show a progress Dialog until the images get loaded fully. I have overrided the onBackPressed() method, such that when the user presses the back button, the activity will be finished.

But if I press the back button when the progress dialog is being displayed, the back key event was not called. So I tried providing progressDialog.setCancelable(true) . So this now allows me to dismiss the progress Dialog, but my back key event is not being called anyway and so my activity loads images in the background.

So how do I make both the progressDialog and activity to be stopped when the user presses the back key.

Use Dialog.setOnCancelListener to cancel your background task

Ok. I have found out a solution at last.

progressDialog.setCancelable(true);
    progressDialog.setOnCancelListener(new OnCancelListener() {

        public void onCancel(DialogInterface dialog) {

        Log.i("inside on cancel","Cancel Called");  
        finish(); //If you want to finish the activity.
        }
    });

Load your images in a different thread. When the user indicates they want to cancel the load, set a flag that is checked in the loading thread's processing loop. You can also call the loading thread's interrupt() method to handle those cases where the thread is stuck in a wait() or sleep() or something.

Use onKeyDown() method, however you'd have to check whether the dialog is showing, whether the button being pressed is the 'back' button, and you should also make a call to super.onKeyDown() to make sure that the default method is also executed.

 public boolean onKeyDown(int keyCode, KeyEvent event) 

{

if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing())
{
    // DO WHATEVER YOU WANT
}

// Call super code so we dont limit default interaction
super.onKeyDown(keyCode, event);

return true;
}

Can you paste the code for correct answer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM