The ‘Back‘ button has many different uses in many different android apps. While some app developers use it to close their apps, some use it to traverse back to the app’s previous activity. Many apps require the user to press the ‘Back’ button two times within an interval to successfully close the application, which is considered the best practice.
Why implement this in the app?
- It adds a better UX to the app providing the user with a satisfying experience.
- It acts as a confirmation in case the user presses the ‘Back’ button by mistake.
Step 1: Create a new Android Studio project
Step 2: Working with activity_main.xml file
The above layout looks like this:
Step 3: Working with MainActivity.java file
Now comes the main part of the app. In order to check when the ‘BACK’ button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the ‘BACK’ button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don’t exit. Here’s how the MainActivity.java looks like:
In the above code, when the user presses the ‘BACK’ button once, they are greeted with a toast asking them to press it again to exit. If the user then presses ‘BACK’ again within 2 seconds(2000ms), then the app is closed, otherwise, we remain there.
Output: Run on Emulator
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- How to Detect Long Press in Android?
- How to Listen for Volume Button and Back Key Events Programmatically in Android?
- System.exit() in Java
- Java System.exit(0) vs C++ return 0
- How to implement View Shaker in Android
- How to implement Picture in Picture (PIP) in Android?
- How to implement Options Menu in Android
- How to implement Dark (Night) mode in Android app
- How to implement a TabLayout in Android using ViewPager and Fragments
- Implement Zoom In or Zoom Out in Android
- Implement customized TimePicker in Android using SnapTimePicker
- Implement reverse AnimatedVectorDrawables using MorphView in Android
- How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
- How to Implement Swipe Down to Refresh in Android
- How to Implement TextWatcher in Android?
- Android | Android Application File Structure
- Android | AdMob Interstitial Ads for Android Studio
- Android | How to Create/Start a New Project in Android Studio?
- Android | Running your first Android app
- Android | How to add Radio Buttons in an Android Application?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.