Created
March 27, 2020 19:57
-
-
Save vladimirpetrovski/fa4d5ed051a12186eb8c848f5804ecf1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class WiFiScanUseCase(private val context: Context) { | |
| private val wifiManager = | |
| context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager | |
| private val wifiSSID = "My Network" | |
| operator fun invoke(): Completable { | |
| return startScanning() | |
| } | |
| private fun startScanning(): Completable { | |
| return Completable.create { emitter -> | |
| val intentFilter = IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) | |
| val receiver = object : BroadcastReceiver() { | |
| override fun onReceive(ctx: Context?, intent: Intent?) { | |
| val resultList = wifiManager.scanResults.toList() | |
| val cmrList = resultList.filter { it.SSID == wifiSSID } | |
| Timber.v("Filtered list: ${cmrList.map { it.SSID }}") | |
| when { | |
| cmrList.size == 1 -> emitter.onComplete() | |
| cmrList.isEmpty() -> emitter.tryOnError(IllegalArgumentException("Can not find a device.")) | |
| else -> emitter.tryOnError(IllegalArgumentException("More than one items found.")) | |
| } | |
| } | |
| } | |
| Timber.v("Scanning for wifi networks...") | |
| context.registerReceiver(receiver, intentFilter) | |
| emitter.setCancellable { | |
| Timber.v("Unregistering scanning for wifi networks...") | |
| context.unregisterReceiver(receiver) | |
| } | |
| if (!wifiManager.startScan()) { | |
| Timber.w("error startScan") | |
| emitter.onError(IllegalArgumentException("Failed to start scan")) | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment