Код: Выделить всё
const val PERMISSION_BLUETOOTH_SCAN = "android.permission.BLUETOOTH_SCAN"
class BLEScanner(context: Context) {
private val bluetooth = context.getSystemService(Context.BLUETOOTH_SERVICE)
as? BluetoothManager
?: throw Exception("Bluetooth is not supported by this device")
val isScanning = MutableStateFlow(false)
val foundDevices = MutableStateFlow(emptyList())
private val scanner: BluetoothLeScanner
get() = bluetooth.adapter.bluetoothLeScanner
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
Log.d("BTScanning", result.toString())
result ?: return
if (!foundDevices.value.contains(result.device)) {
foundDevices.update { it + result.device }
Log.d("BTDevice", "Device Result: $result.toString()")
} else Log.d("BTScanning", "No devices found")
}
override fun onBatchScanResults(results: MutableList?) {
super.onBatchScanResults(results)
Log.d("BTScanning", "Batch Results: $results.toString()")
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
isScanning.value = false
Log.d("BTScanning", "Scan failed: $errorCode")
}
}
@RequiresPermission(PERMISSION_BLUETOOTH_SCAN)
fun startScanning() {
scanner.startScan(scanCallback)
Log.d("BTScanning", "StartScanning() called")
}
@RequiresPermission(PERMISSION_BLUETOOTH_SCAN)
fun stopScanning() {
scanner.stopScan(scanCallback)
isScanning.value = false
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... no-results