Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 415
Artem Russakovskii Avatar asked Sep 27 '11 02:09

Artem Russakovskii


People also ask

How can I check back button is pressed in Android?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.

How do I close an app from pressing the back button?

If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.


2 Answers

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);
    }
}
like image 67
Darren Kopp Avatar answered Oct 08 '22 16:10

Darren Kopp


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.

like image 29
Russell Davis Avatar answered Oct 08 '22 16:10

Russell Davis