'Is there a Jetpack Compose equivalent for android:keepScreenOn to keep screen alive?

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?



Solution 1:[1]

This one should be safe from any interference if you have multiple usages in the same composition:

@Composable
fun KeepScreenOn() = AndroidView({ View(it).apply { keepScreenOn = true } })

Usage is then as simple as that:

if (screenShallBeKeptOn) {
    KeepScreenOn()
}

Solution 2:[2]

In a more Compose way:

@Composable
fun KeepScreenOn() {
    val currentView = LocalView.current
    DisposableEffect(Unit) {
        currentView.keepScreenOn = true
        onDispose {
            currentView.keepScreenOn = false
        }
    }
}

This will be disposed of as soon as views disappear from the composition. Usage is as simple as:

@Composable
fun Screen() {
    KeepScreenOn()
}

Solution 3:[3]

This is how I implemented mine

In my Composable function I have a button to activate the FLAG_KEEP_SCREEN_ON or clear FLAG_KEEP_SCREEN_ON

@Composable
fun MyButton() {
    var state by rememberSaveable {
        mutableStateOf(false)
    }

    val context = LocalContext.current

    Button(
       ...
       modifier = Modifier
            .clickable {
                state = !state
                keepScreen(state, context)
            }
       ...
     )
}

fun keepScreen(state: Boolean, context : Context) {
   val activity = context as Activity
   if(state) {
     activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
   }else {
   activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis CAD
Solution 2 FireZenk
Solution 3 Ashaluwala Kazeem