https://kotlinlang.org logo
#compose
Title
# compose
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
Copy code
@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)
    }
  }
}
👌 2
6 Views