Open In App

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

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
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. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color to the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




import androidx.compose.ui.graphics.Color
  
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
  
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Working with MainActivity.kt file. 

Navigate to app>java>your app’s package name>MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail.

Kotlin




import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
  
class MainActivity : ComponentActivity() {
    @RequiresApi(Build.VERSION_CODES.M)
    private var pressedTime: Long = 0
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // on the below line we are specifying the theme as the scaffold.
                    Scaffold(
                        // in scaffold we are specifying the top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "GFG",
  
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
  
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
  
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling connection information method to display UI
                        pressBackAgainToExit()
                    }
                }
            }
        }
    }
  
    // on below line we are calling on back press method.
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onBackPressed() {
        // on below line we are checking if the press time is greater than 2 sec
        if (pressedTime + 2000 > System.currentTimeMillis()) {
            // if time is greater than 2 sec we are closing the application.
            super.onBackPressed()
            finish()
        } else {
            // in else condition displaying a toast message.
            Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_SHORT).show();
        }
        // on below line initializing our press time variable 
        pressedTime = System.currentTimeMillis();
    }
}
  
// on below line we are creating contact picker function.
@Composable
fun pressBackAgainToExit() {
    // on below line we are creating variable for activity.
    val activity = LocalContext.current as Activity
    // on below line we are creating a column,
    Column(
        // on below line we are adding a modifier to it,
        modifier = Modifier
            .fillMaxSize()
            // on below line we are adding a padding.
            .padding(all = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        // on below line we are adding a text for heading.
        Text(
            // on below line we are specifying text
            text = "Press Back Again to Exit in Android",
            // on below line we are specifying text color, font size and font weight
            color = greenColor, fontSize = 20.sp, fontWeight = FontWeight.Bold
        )
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads