代码之家  ›  专栏  ›  技术社区  ›  Archie G. Quiñones

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

  •  0
  • Archie G. Quiñones  · 技术社区  · 7 年前

    我最近才知道 Coroutines 我正尽我所能把它落实到每一件事上。

    我知道你可以把回电转换成 coroutine

    是否可以将 Broadcast Receiver coroutines 通过使用 suspendCoroutine

    我该怎么做?

    0 回复  |  直到 6 年前
        1
  •  1
  •   fal    6 年前

    这是一种方法(由 leonardkraemer this 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()
        }
    }