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();
}
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.
– Emerson Rocha
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.
– Neto Marin