Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Implement Swipe Down to Refresh in Android
Next article icon

How to Implement Press Back Again to Exit in Android?

Last Updated : 12 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

https://media.geeksforgeeks.org/wp-content/uploads/20240802192306/pressbackagaintoexit.mp4

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.

Approach

Step 1: Create a new Android Studio project

Please refer to this article How to create a new project in Android Studio to see in detail how to create a new Android Studio project. Note that choose Java as the programming language.

Step 2: Working with activity_main.xml file

In this example, we will have only a single layout, activity_main.xml which will contain an ImageView and a TextView.

This is how our activity_main.xml looks like:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity"     android:background="#388e3c"     android:orientation="vertical">      <ImageView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:src="@drawable/gfglog"/>        <TextView         android:padding="15dp"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="This was written at GeeksforGeeks"         android:textColor="#f5f5f5"         android:textSize="30sp"         android:gravity="center_horizontal"/>  </LinearLayout> 

The above layout looks like this:

output ui

Layout Output

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:

MainActivity.java
package org.geeksforgeeks.pressbackexit;  import android.os.Bundle; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {     private long pressedTime;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);     }      @Override     public void onBackPressed() {          if (pressedTime + 2000 > System.currentTimeMillis()) {             super.onBackPressed();             finish();         } else {             Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_SHORT).show();         }         pressedTime = System.currentTimeMillis();     } } 

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

https://media.geeksforgeeks.org/wp-content/uploads/20200811200701/Android-Emulator---Pixel_2_API_29_5554-2020-08-11-19-48-48_Trim.mp4


Next Article
How to Implement Swipe Down to Refresh in Android

A

agarwalkeshav8399
Improve
Article Tags :
  • Android
  • Java
  • Android Projects
Practice Tags :
  • Java

Similar Reads

  • How to Implement Press Back Again to Exit in Android using Jetpack Compose?
    The back button is used in many android applications. It is generally used to navigate to the previous page or simply exit the application. Many applications nowadays ask users to press the back button twice to exit the application. In this article, we will be building a simple application in which
    4 min read
  • How to Implement Swipe Down to Refresh in Android
    Certain applications show real-time data to the users, such as stock prices, availability of a product on online stores, etc. Showing real-time data requires continuous syncing of the application, and could be possible by implementing a program such as a thread. A Thread could be initiated by the ap
    3 min read
  • How to Implement onBackPressed() in Fragments in Android?
    In Android, the Fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. onBac
    3 min read
  • How to Go Back to Previous Activity in Android?
    In this article, we are going to see how we can add a back button to an activity through which we can go back to its previous activity. This can be achieved with just a few lines of code, which is explained in the steps below Step by Step ImplementationStep 1: Create a New Project in Android StudioT
    3 min read
  • How to Implement Polling in Android?
    Many times you may have seen on some apps like youtube, LinkedIn, etc. polling is done and users choose their options whatever they want to choose. Here we are going to implement polling in Android Studio. What we are going to build in this article? In this article, we will ask the user a question a
    4 min read
  • How to Implement OTP View in Android?
    An OTP View or PinView in android is a widget that allows users to enter their PIN, OTP, etc. They are generally used for two-factor authentication or phone number verification by OTP. A sample video is given below to get an idea about what we are going to do in this article. Note: In order to imple
    2 min read
  • How to Implement Custom Dialog Maker in Android?
    In this article, we are going to make an application of Custom Dialog Maker in android studio. In this application, we can create dialogs of our own choice of style, type, and animation. What is a dialog? A dialog is a small window that prompts the user to make a decision, provide some additional in
    5 min read
  • How to Implement TextWatcher in Android?
    If an application contains a login form to be filled by the user, the login button should be disabled (meaning: it shouldn't be clickable). When the user enters the credentials of the form the button should be enabled to click for the user. So in this article, we are implementing a Text Watcher to t
    4 min read
  • How to implement View Shaker in Android
    View Shaker is an animation in which, the UI of screen vibrates for a limited period of time. This can be implemented on the whole layout or some particular widget. It is a very common effect that developers use, especially to show incorrect credentials. View Shaker helps us to animate the widgets.
    3 min read
  • How to Disable Back Press Button in Android?
    Physical keys on Android let users lock the phone, switch off the device, control volume, go back, go home and display background applications. Between all the keys, the back button is used the most in applications for navigating between activities. However, if the navigation stage reaches the start
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences