Android: How can I detect if the Back button will exit the app (i.e. this is the last activity left on the stack)?-ThrowExceptions

Exception or error:

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.


How to solve:

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)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //Stop the activity
        .setNegativeButton(, null)

        return true;
    else {
        return super.onKeyDown(keyCode, event);


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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *