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 :)
Here is the full working code. And also don't forget to remove the callbacks so that it don't cause a memory leak in the app. :)
I use this
use to in event
onBackPressed
or
ExitApp.now(this,R.string.double_back_pressed)
for change seconds need for close, specified miliseconds
ExitApp.now(this,R.string.double_back_pressed,5000)
Here, I have generalized write the code for N tap counts. The code is similarly written for the Enable Developer option in android device phone. Even you can use this to enable features while developer testing the app.
Call askToExit() on backpress or logout option.
Zefnus's answer using System.currentTimeMillis() is the best one (+1). The way I did it is not better than that, but still posting it to add to the above ideas.
If the toast is not visible when the back button is pressed, the toast is displayed, whereas, if it is visible (back has already been pressed once within the last
Toast.LENGTH_SHORT
time), then it exits.Just thought I would share how I did it in the end, I just added in my activity:
And it just works exactly as I want. Including the reset of the state whenever the activity is resumed.
For this purpose I have implemented the following function: