Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Warning when user click on back button to Exit App

I was wondering how you would have a warning appear when the user tries to exit the app? So this includes if they are pressing the back button too. What would be the best way to do this?

I have seen this done on some mainstream games.

like image 254
Nick Avatar asked Jan 27 '26 09:01

Nick


1 Answers

you may add onBackPressed() in your Application subclass to intercept the back button:

public static void onBackPressed(final Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.on_back_button_title);
    builder.setMessage(R.string.on_back_button_message);
    builder.setPositiveButton(R.string.yes, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            activity.finish();
        }
    });
    builder.setNegativeButton(R.string.no, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.show();
}
like image 146
lenik Avatar answered Jan 29 '26 23:01

lenik