3

I'm currently working on an app that uses a lot the back button of android devices. I was wondering how to check if the activity is the last one and if the user presses back again, it doesn't exit the app except if the user presses back again, like with the 9gag app.

Thank you!

dequec64
  • 923
  • 1
  • 8
  • 26
  • 1
    Duplicate of http://stackoverflow.com/questions/2257963/how-to-show-a-dialog-to-confirm-that-the-user-wishes-to-exit-an-android-activity – Rohit5k2 Feb 01 '16 at 14:23

4 Answers4

7
@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();
}
Henry
  • 1,042
  • 2
  • 17
  • 47
4

With the method Activity.isTaskRoot() you can check if the user will exit the app on pressing the back button.

Then you just have override onBackPressed() to handle it differently than usual.

Daniel Zolnai
  • 16,487
  • 7
  • 59
  • 71
3

Here example:

private boolean doubleBackToExitPressedOnce;
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, this.getResources().getString(R.string.exit_toast), Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}

DrawerLayout block is optional.

Volodymyr Kulyk
  • 6,455
  • 3
  • 36
  • 63
0

This will not Worke OnBackpress method

@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();
}
Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34