24

I'd like to warn the user if the back press is going to finish the last activity on the stack, thereby exiting the app. I'd like to pop up a little toast and detect a 2nd back press within the next few seconds and only then call finish().

I already coded the back press detection using onBackPressed(), but I can't find an obvious way to see how many activities are left on the back stack.

Thanks.

Seraphim's
  • 12,559
  • 20
  • 88
  • 129
Artem Russakovskii
  • 21,516
  • 18
  • 92
  • 115

2 Answers2

25

The reddit is fun app does this by overriding the onKeyDown method:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK && isTaskRoot()) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setMessage(R.string.really_quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //Stop the activity
                finish();    
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();

        return true;
    }
    else {
        return super.onKeyDown(keyCode, event);
    }
}
Darren Kopp
  • 76,581
  • 9
  • 79
  • 93
  • 1
    isTaskRoot() seems like the cleanest method without requiring extra permissions. I think this is the winner. – Artem Russakovskii Sep 27 '11 at 19:33
  • What is mSettings here? – berserk Jun 16 '14 at 13:46
  • @berserk mSettings is just the a reference to the application settings determining if we want to display confirmation dialog or not. it's not critical in this example. – Darren Kopp Jun 16 '14 at 16:31
  • It is not detecting if this is the final activity. It is returning false. I was having only one activity left in stack. – berserk Jun 17 '14 at 07:02
  • isTaskRoot() returns true even if back does not result in exiting the app. i.e..., if you are displaying a bunch of fragments – Jia Tse Mar 07 '16 at 20:43
3

The droid-fu library does this by checking the stack of running tasks and seeing if the next task is the android home screen. See handleApplicationClosing at https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/activities/BetterActivityHelper.java.

However, I would only use this approach as a last resort since it's quite hacky, won't work in all situations, and requires extra permissions to get the list of running tasks.

Russell Davis
  • 8,319
  • 4
  • 40
  • 41