https://kotlinlang.org logo
Title
c

Chris Fillmore

05/27/2022, 4:48 PM
Any prefab way to handle screen on/off in Compose? i.e. a Compose-y version of this https://stackoverflow.com/a/19019742
I’ve just written this
@Composable
fun ScreenOnOffHandler(onChange: (screenOn: Boolean) -> Unit) {
  val context = LocalContext.current
  DisposableEffect(context) {
    val intentFilter = IntentFilter().apply {
      addAction(Intent.ACTION_SCREEN_ON)
      addAction(Intent.ACTION_SCREEN_OFF)
    }
    val receiver = object : BroadcastReceiver() {
      override fun onReceive(context: Context, intent: Intent) {
        onChange(intent.action == Intent.ACTION_SCREEN_ON)
      }
    }
    context.registerReceiver(receiver, intentFilter)
    onDispose {
      context.unregisterReceiver(receiver)
    }
  }
}
:nice: 2