How do I know if the user really wants to come back, when click the back button of the phone?

Asked

Viewed 596 times

0

I have a activity which stores certain data, and when the user presses the back button (Avd Hardware Button, for example), the application does not return to the previous screen, but rather open a dialog screen asking if the user wants to return to the previous screen knowing that it will lose the saved data.

How to capture this event?

  • 5

    The title of your question is different from the body of the question. In the first you are asking about UX, and in the second about programming.

  • Just commenting that this is not a recommended practice on the Android platform. The back button should ALWAYS return immediately. Save the data in some state if need, or simply let the user lose the data.

2 answers

3


Try using this code:

@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);
}

}

Or this for Android 2.0+

@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setTitle("Closing Activity")
    .setMessage("Are you sure you want to close this activity?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();    
    }

})
.setNegativeButton("No", null)
.show();
}
  • I wouldn’t even consider the first option. Apps below 2.2 don’t even have access to the play store.

  • But you can still install APK’s by transfer.

  • Yes, but if someone has an appliance running Eclair, sell it to the museum for cash :)

  • JP worked perfectly the second way, thank you very much!

3

A little Google gave me the following result:

public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
return true;

}
return super.onKeyDown(keyCode, event);
}

It only checks if the keyevent is equal to the given keycode! Remembering that if you format a little, you can use the code to detect any keypress!

(source: http://nisha113a5.blogspot.com.br/2012/01/intercept-home-key-android.html)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.