5

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

Reza Zeraati
  • 303
  • 1
  • 8

2 Answers2

7

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

Thracian
  • 43,021
  • 16
  • 133
  • 222
  • Thanks a lot. why they made the function private? I see this sometimes, but I don't understand why people do it sometimes. – Reza Zeraati Sep 17 '22 at 11:27
  • 1
    You set visibility of functions for encapsulation. It can be private if you only wish to call from a class that this function is declared. You can set no visibility modifier, kotlin uses public by default, if you need to call from multiple files. I didn't pay attention to its visibility but due to habit i try to set anything private unless more visibility is required – Thracian Sep 17 '22 at 11:30
  • @Thracian the best answer – Hossein Badrnezhad Nov 08 '22 at 15:18
  • How can we do this with a navigation graph – Mohd Qasim Jan 02 '23 at 07:15
1

@Thrancian 's answer didn't seem to go the way I wanted it to. Because in my tests, I had to hit the back button three times to exit the app.

But I modified it to meet my needs.

@Composable
fun BackPressSample2() {
    var exit by remember { mutableStateOf(false) }
    val context = LocalContext.current

    LaunchedEffect(key1 = exit) {
        if (exit) {
            delay(2000)
            exit = false
        }
    }

    BackHandler(enabled = true) {
        if (exit) {
            context.startActivity(Intent(Intent.ACTION_MAIN).apply {
                addCategory(Intent.CATEGORY_HOME)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            })
        } else {
            exit = true
            Toast.makeText(context, "Press again to exit", Toast.LENGTH_SHORT).show()
        }
    }
}
OCN Yang
  • 21
  • 4