Open In App

Exit From App on Double Click of Back Button in Android using Kotlin

Last Updated : 06 Dec, 2021
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. So it is a good practice to exit from an app with a double click of the back button. As some time user can press the back button by mistake. So, to ensure that, whether the user really wants to exit from the app we implement this feature.

So in this article, we will learn How to implement an exit feature with a double click of the back button in our app. We will implement this feature in our app using kotlin.

Note: To implement in Java refer to this article: How to Implement Press Back Again to Exit in Android?

Step by step Implementation

Step 1: Create a new android project in kotlin.

Step 2: XML layout for activity, In this project we only have single activity. And the XML layout design will also be very simple.


<?xml version="1.0" encoding="utf-8"?>
        app:layout_constraintTop_toTopOf="parent" />
        android:text="Welcome to GeeksForGeeks"
        app:layout_constraintVertical_bias="0.303" />

You can customize the layout.

Step 3: Now in mainActivity, We will override onBackPressed() method. With the first press of the back button, we will store the current system time, and display a toast. If the user presses the back button again within 3 seconds we will call the finish() method.


package com.ayush.gfg_exit
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
    var backPressedTime: Long = 0
    override fun onCreate(savedInstanceState: Bundle?) {
    override fun onBackPressed() {
        if (backPressedTime + 3000 > System.currentTimeMillis()) {
        } else {
            Toast.makeText(this, "Press back again to leave the app.", Toast.LENGTH_LONG).show()
        backPressedTime = System.currentTimeMillis()

So our app is ready.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads