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 :)
Some Improvements in Sudheesh B Nair's answer, i have noticed it will wait for handler even while pressing back twice immediately, so cancel handler as shown below. I have cancled toast also to prevent it to display after app exit.
Sudheesh B Nair's has a nice (and accepted) answer on the question, which i think should have a better alternative such as;
What's wrong with measuring time passed and checking if
TIME_INTERVAL
miliseconds (say 2000) passed since the last back press. The following sample code usesSystem.currentTimeMillis();
to store the timeonBackPressed()
is called;Back on accepted answer critique; Using a
flag
to indicate if it was pressed in lastTIME_INTERVAL
(say 2000) milliseconds and set - reset is viaHandler
'spostDelayed()
method was the first thing to come in my mind. But thepostDelayed()
action should be cancelled when activity is closing, removing theRunnable
.In order to remove the
Runnable
, it must not be declared anonymous, and be declared as member along with theHandler
aswell. ThenremoveCallbacks()
method ofHandler
can be called appropriately.The following sample is the demonstration;
Thanks to @NSouth for contributing; In order to prevent toast message appearing even after the application is closed,
Toast
can be declared as a member - saymExitToast
- and can be cancelled viamExitToast.cancel();
just beforesuper.onBackPressed();
call.When HomeActivity contain navigation drawer and double backPressed() funtion to exit app. (Don't forget to initilize global variable boolean doubleBackToExitPressedOnce = false;) new handler after 2 sec set doubleBackPressedOnce variable to false
In java
in kotlin
For the activity whose is having Navigation Drawer, Use the following code for OnBackPressed()