Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user from exiting an app when back button is pressed [duplicate]

I have developed an app working successfully, but there are two activities, first is the splash screen and second one is webview. Now problem is that when back button is pressed it closes the App and exits, however the back, forward and refresh button are there in the app for internal navigation. So how to show an are you sure to exit dialog or to prevent user from deactivating the back key.

like image 323
Manan Gupta Avatar asked Nov 29 '25 16:11

Manan Gupta


2 Answers

Something like this by overriding onBackPressed() method of Activity class:

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setMessage("Are you sure you want to exit?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyActivity.super.onBackPressed();
                }
            })
            .setNegativeButton("No", null)
            .show();


}
like image 51
nikis Avatar answered Dec 01 '25 07:12

nikis


Just do,

   @Override
public void onBackPressed() {

  //  super.onBackPressed();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

            // Setting Dialog Title
            alertDialog.setTitle("Exit alert");
             alertDialog.setMessage("Do You want Exit??");
            alertDialog .setIcon(R.drawable.galleryalart);


            alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {

                          dialog.cancel();
                }
            });


            alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

             [youractivity].super.onBackPressed();


                }
            });


            alertDialog.show();



}
like image 31
Sekhar Madhiyazhagan Avatar answered Dec 01 '25 05:12

Sekhar Madhiyazhagan