是否可以将BroadcastReciever转换为协程?

时间:2019-01-02 07:23:06

标签: android broadcastreceiver kotlinx.coroutines

所以我最近学到了Coroutines,我正在努力将其应用于所有方面。

我希望您可以将回调转换为coroutine

是否可以使用Broadcast Receivercoroutines转换为suspendCoroutine

有人可以指导我如何做吗?

1 个答案:

答案 0 :(得分:1)

这是一种方法(由leonardkraemerthis answer提供):

suspend fun Context.getCurrentScanResults(): List<ScanResult> {
    val wifiManager = getSystemService(Context.WIFI_SERVICE) as? WifiManager ?: return listOf()
    return suspendCancellableCoroutine { continuation ->
        val wifiScanReceiver = object : BroadcastReceiver() {
            override fun onReceive(c: Context, intent: Intent) {
                if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
                    unregisterReceiver(this)
                    continuation.resume(wifiManager.scanResults)
                }
            }
        }
        continuation.invokeOnCancellation {
            unregisterReceiver(wifiScanReceiver)
        }
        registerReceiver(wifiScanReceiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
        wifiManager.startScan()
    }
}