Open In App

How to Implement Press Back Again to Exit in Android using Jetpack Compose?

Last Updated : 26 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 we will implement press back again to exit the android application using Jetpack Compose. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Select Empty Activity as the template. Select Kotlin as the programming language.

Step 2: Working with MainActivity.kt file. 

Navigate to app > java+kotlin > {package-name} > MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail.

MainActivity.kt:

Kotlin
package com.geeksforgeeks.demo

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.*

class MainActivity : ComponentActivity() {
    private var pressedTime: Long = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            PressBackAgainToExit()
        }
    }

    // calling on back press method.
    override fun onBackPressed() {
        // checking if the press time is greater than 2 sec
        if (pressedTime + 2000 > System.currentTimeMillis()) {
            // if time is greater than 2 sec, closing the application
            super.onBackPressed()
            finish()
        } else {
            // in else condition displaying a toast message
            Toast.makeText(baseContext, "Press back again to exit", Toast.LENGTH_SHORT).show();
        }
        // initializing press time variable
        pressedTime = System.currentTimeMillis();
    }
}

@Composable
fun PressBackAgainToExit() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(all = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Text(
            text = "Press Back Again to Exit in Android",
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold
        )
    }
}

Output


Article Tags :

Similar Reads