-
-
Save Arunshaik2001/5ab19c36f6cce5c423ddd09e38980e01 to your computer and use it in GitHub Desktop.
This file contains 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
fun startScan() { | |
scanFilters = buildScanFilters() | |
scanSettings = buildScanSettings() | |
if (!adapter.isMultipleAdvertisementSupported) { | |
_viewState.value = DeviceScanViewState.AdvertisementNotSupported | |
return | |
} | |
if (scanCallback == null) { | |
scanner = adapter.bluetoothLeScanner | |
_viewState.value = DeviceScanViewState.ActiveScan | |
Handler().postDelayed({ stopScanning() }, SCAN_PERIOD) | |
scanCallback = DeviceScanCallback() | |
scanner?.startScan(scanFilters, scanSettings, scanCallback) | |
} | |
} | |
private fun buildScanFilters(): List<ScanFilter> { | |
val builder = ScanFilter.Builder() | |
builder.setServiceUuid(ParcelUuid(SERVICE_UUID)) | |
val filter = builder.build() | |
return listOf(filter) | |
} | |
private fun buildScanSettings(): ScanSettings { | |
return ScanSettings.Builder() | |
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) | |
.build() | |
} | |
private inner class DeviceScanCallback : ScanCallback() { | |
override fun onBatchScanResults(results: List<ScanResult>) { | |
super.onBatchScanResults(results) | |
for (item in results) { | |
item.device?.let { device -> | |
scanResults[device.address] = device | |
} | |
} | |
Log.i(TAG, scanResults.toString()) | |
_viewState.value = DeviceScanViewState.ScanResults(scanResults) | |
} | |
override fun onScanResult( | |
callbackType: Int, | |
result: ScanResult | |
) { | |
super.onScanResult(callbackType, result) | |
result.device?.let { device -> | |
scanResults[device.address] = device | |
} | |
Log.i(TAG, scanResults.toString()) | |
_viewState.value = DeviceScanViewState.ScanResults(scanResults) | |
} | |
override fun onScanFailed(errorCode: Int) { | |
super.onScanFailed(errorCode) | |
val errorMessage = "Scan failed: $errorCode" | |
_viewState.value = DeviceScanViewState.Error(errorMessage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment