Search code examples
androidauthenticationandroid-intentandroid-activitydialog

Handling backpress on activity


I have 2 activity called Login and Main in login activity there is code block that makes this functionality that if I click back in Main activity it will close the app instead of going back to login activity but I want to handle back press and maybe with one dialog "you are going to exit the app you sure? " or something like this.

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

this code block is in my login actvity


Solution

  • copy and paste the below code in your onBackPressed() method in MainActivity.java.

    new AlertDialog.Builder(MainActivity.this)
                .setTitle("Confirm close")
                .setMessage("Are you sure want to close app")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which {
                        finish();
                    }
                 }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which {
                       dialog.dismiss();
                     }
                 }).create().show();