I've noticed this pattern in a lot of Android apps and games recently: when clicking the back button to "exit" the application, a Toast
comes up with a message similar to "Please click BACK again to exit".
I was wondering, as I'm seeing it more and more often, is that a built-in feature that you can somehow access in an activity? I've looked at the source code of many classes but I can't seem to find anything about that.
Of course, I can think about a few ways to achieve the same functionality quite easily (the easiest is probably to keep a boolean in the activity that indicates whether the user already clicked once...) but I was wondering if there's something already here.
EDIT: As @LAS_VEGAS mentioned, I didn't really mean "exit" in the traditional meaning. (i.e. terminated) I meant "going back to whatever was open before the application start activity was launched", if that makes sense :)
This is the same of the accepted and most voted response but this snipped used Snackbar instead of Toast.
I Think this handler helps to reset the variable after 2 second.
My solution using snackbar:
Simple and stylish.
Here is another way... using the CountDownTimer method
Recently, I needed to implement this back button feature in an app of mine. The answers on the original question were useful, but I had to take two more points into consideration:
Based on the answers and comments, I created the following code:
The code above assumes that the support library is used. If you use fragments but not the support library, you want to replace
getSupportFragmentManager()
bygetFragmentManager()
.Remove the first
if
, if the back button is never cancelled. Remove the secondif
, if you don`t use fragments or a fragment back stackAlso, it is important to be aware that the method
onBackPressed
is supported since Android 2.0. Check this page for an elaborate description. To make the back press feature work on older versions as well, add the following method to your activity:In my case, I've depend on
Snackbar#isShown()
for betterUX
.