kotlinandroid-jetpack-composeandroid-jetpack

How to set Double back press Exit in Jetpack Compose?


There are some tutorials on YouTube about how to set double back press exit in XML android, but most of them are in JAVA and None of them are in Jetpack Compose.

So how can we set that Double back press in Jetpack Compose?

I mean that thing that ask us in a Toast to press back again if we are sure to Exit. Thanks for help


Solution

  • This sample shows Toast on first touch and waits for 2 seconds to touch again to exit app otherwise goes back to Idle state.

    sealed class BackPress {
        object Idle : BackPress()
        object InitialTouch : BackPress()
    }
    
    @Composable
    private fun BackPressSample() {
        var showToast by remember { mutableStateOf(false) }
    
        var backPressState by remember { mutableStateOf<BackPress>(BackPress.Idle) }
        val context = LocalContext.current
    
        if(showToast){
            Toast.makeText(context, "Press again to exit", Toast.LENGTH_SHORT).show()
            showToast= false
        }
    
    
        LaunchedEffect(key1 = backPressState) {
            if (backPressState == BackPress.InitialTouch) {
                delay(2000)
                backPressState = BackPress.Idle
            }
        }
    
        BackHandler(backPressState == BackPress.Idle) {
            backPressState = BackPress.InitialTouch
            showToast = true
        }
    }
    

    enter image description here