在广播接收器上运行协程函数

MKi*_*mid 7 android coroutine broadcastreceiver kotlin

我正在制作一个闹钟应用程序,并使用 AlarmManager 来设置闹钟。在 AlarmManager 上运行 setAlarm 后,我使用 Room 保存每个闹钟,这样如果手机关闭,我可以稍后恢复它们。

我在设备启动后使用 Android 开发人员站点的指南运行 BroadcastReceiver: https: //developer.android.com/training/scheduling/alarms#boot

我的想法是通过 onReceive 方法从 Room 获取警报但是 Room 使用挂起乐趣来获取警报,但我无法在 onReceive 上运行它,因为 BroadcastReceiver 没有生命周期

我怎样才能达到类似的结果?

Ten*_*r04 31

BroadcastReceiver 文档中的本节提供了如何执行此操作的示例。

您可以使用扩展函数来清理它:

fun BroadcastReceiver.goAsync(
    context: CoroutineContext = EmptyCoroutineContext,
    block: suspend CoroutineScope.() -> Unit
) {
    val pendingResult = goAsync()
    @OptIn(DelicateCoroutinesApi::class) // Must run globally; there's no teardown callback.
    GlobalScope.launch(context) {
        try {
            block()
        } finally {
            pendingResult.finish()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的接收器中,您可以像下面一样使用它。块中的代码goAsync是一个协程。请记住,您不应该Dispatchers.Main在此协程中使用它,并且它必须在 10 秒内完成。

override fun onReceive(context: Context, intent: Intent) = goAsync {
    val repo = MyRepository.getInstance(context)
    val alarms = repo.getAlarms() // a suspend function
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)