I have a Composable that uses a Handler to slowly update the alpha of an image inside a composable. However, I'm seeing that the screen turns off before the animation could complete.
In XML layouts, we could keep it alive using
android:keepScreenOn
or
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
Is there a way to do this using compose without using the wake lock permission?
You can use LocalActivity
to get activity, and it has a window on which you can apply needed flags.
In such cases, when you need to run some code on both view appearance and disappearance, DisposableEffect
can be used:
@Composable
fun KeepScreenOn() {
val activity = LocalActivity.current
DisposableEffect(Unit) {
val window = activity?.window
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
onDispose {
window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
}
Usage: when screen appears flag is set to on, and when disappears - it's cleared.
@Composable
fun Screen() {
KeepScreenOn()
}
As @Louis CAD correctly pointed out, you can have problems if you use this "view" in many views: if one view appears that uses it, and then disappears previous views that also used it, it will reset the flag.
I haven't found a way of tracking flags
state to update the view, I think @Louis CAD solution is OK until Compose have some system support.