Skip to content

Introduce CoroutineBroadcastReceiver #6000

@TimoPtr

Description

@TimoPtr

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 #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.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions