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 :)
Based upon the correct answer and suggestions in comments, I have created a demo which works absolutely fine and removes the handler callbacks after being used.
MainActivity.java
I hope it will be helpful !!
This also helps when you have previous stack activity stored in stack.
I have modified Sudheesh's answer
A slightly better method than Zefnus I think. Call System.currentTimeMillis() just one time and omit
return;
:Finally create a onBackPressedMethod as Follows:
This works correctly, i have tested. and I think this is much simpler.
I know this is a very old question, but this is the easiest way to do what you want.
I know this isn't the best method, but it works fine!
Process Flow Diagram:
Java Code: