Is there a compose equivalent to `android:keepScreenOn`?
a
Is there a compose equivalent to
android:keepScreenOn
?
k
You can get the activity from
LocalContext
, and use
DisposableEffect()
to create a composable that when in the composition tree, prevents the screen from being turned off.
Copy code
@Composable
fun KeepScreenOn() {
    val activity = findFromContext<Activity>()!!
    val flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
    DisposableEffect(activity) {
        activity.window.addFlags(flag)
        onDispose {
            activity.window.clearFlags(flag)
        }
    }
}

@Composable
inline fun <reified T> findFromContext(): T? {
    var context = LocalContext.current
    while (context !is T) {
        context = (context as? ContextWrapper)?.baseContext ?: return null
    }
    return context
}
a
Thanks! It works perfectly but I modified it a little bit
Copy code
@Composable
fun KeepScreenOn(content: @Composable () -> Unit) {
    val window = LocalWindow.current

    DisposableEffect(window) {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        onDispose {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }
    }

    content()
}
a
You could skip the content parameter entirely and simply call this with no parameters somewhere in your UI, there's not much benefit in having other UI be child content of it. Since you're effectively modifying a root view parameter, you might also look for a way to stash a reference count with the root view, say in a view tag or something, so that you don't end up with strange results if there's more than one instance of this composable in your composition
👍 1
c
@André Kindwall Is
LocalWindow
something you created yourself? I don't see it documented anywhere, but would love a way to access the window from a Composable!
k
Pretty sure he created it himself. You can get
Window
from
LocalContext
.
c
@knthmn Does it require casting the Context as an Activity? Is that always guaranteed to be safe?
k
Similar code is used by
BackHandler
for searching
OnBackPressedDispatcherOwner
from the
context
. https://androidx.tech/artifacts/activity/activity-compose/1.3.0-alpha05-source/androidx/activity/compose/BackHandler.kt.html https://androidx.tech/artifacts/activity/activity-compose/1.3.0-beta01-source/androidx/activity/compose/ActivityComposeUtils.kt.html If you use your composables from a fragment you need to handle it separately.
An alternative is to provide
Window
as a composition local
246 Views