Open In App
Related Articles

How to Implement Press Back Again to Exit in Android?

Improve Article
Save Article
Like Article

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

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:


<?xml version="1.0" encoding="utf-8"?>
        android:text="This was written at GeeksforGeeks"

The above layout looks like this:

output ui

Layout Output

Step 3: Working with 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 looks like:

package org.geeksforgeeks.pressbackexit;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private long pressedTime;
    protected void onCreate(Bundle savedInstanceState) {
    public void onBackPressed() {
        if (pressedTime + 2000 > System.currentTimeMillis()) {
        } 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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 01 Sep, 2020
Like Article
Save Article
Similar Reads
Related Tutorials