Is it possible to detect if the app is running in ...
# compose
m
Is it possible to detect if the app is running in the background? I have a job that I would like to run when the user is displaying the app but not when the user swipes away the app
k
This is neither Compose nor Kotlin, but a general Android question that should be directed to general Android forum(s) / Slack server(s)
m
You can ask the same question for desktop too, so it is not just an Android thing.
k
And the same would apply for desktop - neither Compose nor Kotlin specific, so it would be for Stack Overflow or something similar
m
But if I would like to detect it in a compose app for both iOS and Android?
m
@Kirill Grouchnikov I disagree on that. Compose should provide a platform-agnostic way to handle the basics of the life-cycle of GUI applications. @Magnus Lundberg At the moment you have to implement that with the features of the relevant platform because there is no common solution yet. E.g., on desktop I handled it this way:
Copy code
fun main(args: Array<String>) {

    ModelBridge.initialize(args)
    ModelBridge.configure()

    application(exitProcessOnExit = false) { // This is needed so that ModelBridge.stop() is called at the end.
        val windowState = rememberWindowState(size = DpSize(1200.dp, 900.dp))
        var isMinimized by remember { mutableStateOf(true) }
        Window(
            onCloseRequest = ::exitApplication,
            title = "JavaForumStuttgartApp",
            state = windowState,
        ) {
            LaunchedEffect(windowState) {
                snapshotFlow { windowState.isMinimized }
                    .filter { isMinimized != it }
                    .onEach {
                        isMinimized = it
                        if (isMinimized) ModelBridge.stop() else ModelBridge.start()
                    }
                    .launchIn(this)
            }
            MainView()
        }
    }

    ModelBridge.stop()

    exitProcess(0) // This is needed because we set exitProcessOnExit = false.

}
See the isMinimized state.
👍 2
On iOS you can do it by overriding
Copy code
override fun applicationDidEnterBackground(application: UIApplication) {
for example and on Android you have similar methods in the Activity. All platforms have different life-cycle concepts and you somehow have to handle them all yourself and map them onto the life-cycle requirements of your application.