How Do I Prevent Accidental App Exit w/in Android?
IE: When the he/she presses the back button and reaches the last activity in the BackStack, show a toast to ask if the user wants to exit using the onBackPressed() method.
Also, It needs to function with backStacks for fragments.
You can check when the back key is pressed in the main activity of your app. You can then show user an alertdialog for a confirmation to exit.
This functionality can easily be implemented by overriding main activity's onBackPressed() method. In this example when user presses back button then the app will display a toast for 4 seconds on which time a new back press terminates the app immediately.
ref
You can put it in a BaseActivity that extends Activity like this:
EDIT: ADDED FRAGMENT BACKSTACK COMPATABILITY
For use to detect the last fragment in a bacstack whos application is solely using fragments, I strongly suggest putting your dispatchKeyEvents in a BaseActivity class and implementing the above method like so:
*If you're using 2.0+, onBackPressed() simplifies the amount of code needed so onKeyDown() is not needed.
Per androd patterns recomendation: