How do I know if the user really wants to go back, when I click the back button on my cell phone?

0

I have a activity that stores certain data, and when the user presses the back button (Avd Hardware Button, for example), the application does not go back to the previous screen, but rather opens a dialog screen questioning whether the user wants to return to the previous screen knowing that he will lose the saved data.

How to capture this event?

    
asked by anonymous 05.02.2014 / 18:07

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 one 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();
}
    
05.02.2014 / 18:19
3

A little bit of 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 just checks if keyevent is equal to the given keycode! Remember that if you format a bit, you can use the code to detect any keypress!

(source: link )

    
05.02.2014 / 18:20