When we are implementing an AlertDialog within the android application for asking for permissions within the android application. In that case, we provide 2 options either to grant permissions or close the application. In this article, we will take a look at How to quit an android application programmatically using Jetpack Compose.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt:
package com.geeksforgeeks.demo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import com.geeksforgeeks.demo.ui.theme.DemoTheme
import kotlin.system.exitProcess
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoTheme(dynamicColor = false, darkTheme = false) {
Surface(color = Color.White) {
CloseAppWithAButton()
}
}
}
}
}
@Composable
fun CloseAppWithAButton() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Button(
onClick = {
// this closes the main activity
MainActivity().finish()
// this closes the application
exitProcess(0)
}
) {
Text(text = "Close App")
}
}
}