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 :)
Declare Variable
private boolean doubleBackToExitPressedOnce = false;
The Accepted answer is Best one but if you are using
Android Design Support Library
then you can useSnackBar
for Better Views.There is very simplest way among all these answers.
Simply write following code inside
onBackPressed()
method.You need to define
back_pressed
object aslong
in activity.It is not a good idea to use a Runnable when exit the application, I recently figure out a much simpler way to record and compare the period between two BACK button clicks. Sample code as following:
This will do the trick to exit the application by a double BACK button clicks within a certain delay period which is 2000 millisecond in sample.
It's not a built in functionality. I think it is not even the recommended behavior. Android apps are not meant to exit:
Why dont Android applications provide an "Exit" option?