Skip to content

Instantly share code, notes, and snippets.

@Arunshaik2001
Last active October 26, 2022 15:54
Show Gist options
  • Save Arunshaik2001/5ab19c36f6cce5c423ddd09e38980e01 to your computer and use it in GitHub Desktop.
Save Arunshaik2001/5ab19c36f6cce5c423ddd09e38980e01 to your computer and use it in GitHub Desktop.
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