tags:

views:

101

answers:

2

Hi,

When my android activity pops up a progress dialog, what is the right way to handle when user clicks the back button?

Thank you.

+2  A: 

Make a new dialog object that extends ProgressDialog, then override the public void onBackPressed() method within it.

AndrewKS
Not the cancel button, I am talking about the 'Back button' (one of the physical buttons) at the bottom of the phone.
michael
Have you tried it? The back button should fire the cancel event.
AndrewKS
No. It does not work. I set a breakpoint in onCancel(), it never get called.
michael
Try declaring pd in the scope of the whole activity so it had a reference back to it? I'm not sure. It's working for me.
AndrewKS
I am already doing that.
michael
Updated my answer with a different suggestion.
AndrewKS
A: 

if your not having any luck with the onCancel() method, than you can either write up a onKeyDown() method in your activity to check if the progress dialog is showing and if the back button is pressed...or you can override the onBackPressed() method (again, for the activity) and check if your dialog is showing. alternatively you can extend the ProgressDialog class and override onBackPressed() directly from there...in which case you wouldnt have to check if the dialog is showing.

eg. for activity method:

public void onBackPressed()
{
    if (progressDialog.isShowing())
    {
        // DO SOMETHING
    }
}

the onKeyDown() method would be similar, 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 the default method is also executed.

public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing())
    {
        // DO SOMETHING
    }

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

    return true;
}

with either method, the progressDialog variable/property would obviously have to be in scope and accessible.

chich