click two time back button to exit in android

You must have noticed that in many Android apps, you can exit only after double-clicking on the back button to exit.

A toast message appears when you press the back button once. When you simultaneously press the back button you exit your apps. Also, we will set delay of duration like 2000 milliseconds, 1000 milliseconds.

Why use the back button to “press again to exit”.

Sometimes press the back button by mistake and we exit if you have functionality like “Press again” to exit then can’t exit without a double click.

How to make “double click to exit” in android?

Now we come to the point.

Let’s start a new Android app “Press twice to exit.

Step 1:

Create a new android studio project.

Step 2:

there is a default activity like and  activity_main.xml.

for activity_main UI design.


In the activity_main.xml file, we’ll create a simple message hello world! That is the default.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=""

        android:text="Hello World!"
        app:layout_constraintTop_toTopOf="parent" />


Step 3:

Now, Open class.

In we’ll type some code.

The code is given below.

package com.pd.doubleclick;


import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private long Timeback;

    protected void onCreate(Bundle savedInstanceState) {

    public void onBackPressed() {
        if (System.currentTimeMillis() - Timeback > 1000) {
            Timeback = System.currentTimeMillis();
            Toast.makeText(this, "Press Again to Exit", Toast.LENGTH_SHORT).show();

The above code mentioned that we used some methods.

Let’s understand this method.

onBackPressd(); this method is call when you press the back button twice at the same time.

Now, run your application.

Let’s see the output of back-pressed apps in android.

That shown in the below image

When Press Back Button twice times to exit apps in android studio
Press the back button twice to exit

When you press the back button shown a Toast message.

If you wait after press again then the same Toast message is shown.

We saw that when the user presses the back button two times within 1000 milliseconds then closes the app.

For example, we used 1000 milliseconds. Under 1000 milliseconds you press the second time back button then you out of apps. If you press the back button after 2000 milliseconds you will have to press the back button double time.

You any time as per your requirement. Most applications use 2000 milliseconds of time.

Watch on YouTube

Leave a Reply