android icon indicating copy to clipboard operation
android copied to clipboard

Introduce CoroutineBroadcastReceiver

Open TimoPtr opened this issue 3 months ago • 1 comments

Description

Most of our BroadcastReceiver are using coroutines and all of them are creating a new scope not tight to any lifecycle. According to the documentation of BroadcastReceiver the execution of the onReceive method should end within 10s otherwise the system is going to raise an ANR. There is a way to extend this to 30s using goAsync, but the app is not using it and we probably shouldn't and try to fit everything under 10s.

A parallel can be made with the Worker API Google introduced a CoroutineWorker, the difference is that it has a lifecycle. But still we could use this API to help us design an API to help us/standardize how we deal with coroutine in BroadcastReceiver.

Additional context

This has been first discussed in https://github.com/home-assistant/android/pull/5998

A proposal of API could be

abstract class CoroutineBroadcastReceiver : BroadcastReceiver() {
    final override fun onReceive(context: Context, intent: Intent) {
        GlobalScope.launch {
            withTimeout(10.seconds) {
                onReceiveIntent(context, intent)
            }
        }
    }

    abstract suspend fun onReceiveIntent(context: Context, intent: Intent)
}

No need to create a new scope since this new scope would not be tight to any lifecycle.

TimoPtr avatar Nov 05 '25 07:11 TimoPtr

BaseGlanceEntityWidgetReceiver is impacted by this issue. It means that we are staying more than 5s in the onReceived()

TimoPtr avatar Nov 12 '25 13:11 TimoPtr