Leaving android app with back button
A good way is to wait for a second back
private boolean _doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
Log.i(TAG, "onBackPressed--");
if (_doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this._doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
_doubleBackToExitPressedOnce = false;
}
}, 2000);
}
You can try something like this (shows a dialog to confirm exit):
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
It must be noted as it is mentioned in the comments below that exiting an app with System.exit is not recommended. A more "correct" way would probably be to broadcast an intent on back pressed and if the activities of your application received that intent finish themselves.