tags:

views:

3513

answers:

2

I've been trying to show a "Do you want to exit?", type dialog when user attempts to exit an activity. However can't find the appropriate API hooks. Activity.onUserLeaveHint() initially looked promising, but I can't find a way to stop the activity finishing.

Thanks

+4  A: 
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setMessage(R.string.really_quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
                YourClass.this.finish();    
            }

        })
        .setNegativeButton(R.string.no, null)
        .show();

        return true;
    }
    else {
        return super.onKeyDown(keyCode, event);
    }

}
jax
Also in 2.0 and above there is a new onBackPressed event that is recommended over onKeyDownhttp://developer.android.com/intl/zh-TW/reference/android/app/Activity.html#onBackPressed()There is a section here talking about the changes and new recommended approach.http://developer.android.com/intl/zh-TW/sdk/android-2.0.html
sadboy
Blog post on catching the back key here:http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.htmlNote that this does not allow you to catch other ways the user can leave your app: pressing home, selecting a notification, receiving a phone call, etc.
hackbod
A: 

Thanks, this works great for the back key. Unfortunately it appears onKeyDown is not called with KeyEvent.KEYCODE_HOME when the home key is called. How would you catch this event?

Peter A
This should have been posted as a comment on the above answer. Anyway, you can't override the Home key, as that's the one safe route users have to get directly to a "safe" state, no questions asked. Your `Activity` is (very likely to be) still running when users press Home anyway, it is not `finish`ed.
Christopher