I've been trying to implement an Android BLE Scann...
# android
s
I've been trying to implement an Android BLE Scanner in java with no success, at all. Has anyone had any success with any kotlin libraries or kotlin itself in implementing a BLE scanner? Is it easier than in Android, or just as bad?
m
Not sure if this is exactly what you are looking for, but I have used this code to run a BLE Scan for Android in a playground/sandbox app:
Copy code
private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
    val bluetoothManager = activity?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    bluetoothManager.adapter
}

private val bleScanCallback = object: ScanCallback() {
    override fun onScanFailed(errorCode: Int) {
        super.onScanFailed(errorCode)
    }

    override fun onScanResult(callbackType: Int, result: ScanResult?) {
        super.onScanResult(callbackType, result)
        result?.let {
            viewModel.addBleDevice(it.device)
        }
    }

    override fun onBatchScanResults(results: MutableList<ScanResult>?) {
        super.onBatchScanResults(results)
        results?.forEach { result ->
            viewModel.addBleDevice(result.device)
        }
    }
}

private fun scanForBleDevices() {

    when(ContextCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        true -> {
            Handler().postDelayed({
                bluetoothAdapter?.bluetoothLeScanner?.stopScan(bleScanCallback)
                viewModel.onBleScanFinished()
            }, 5000)

            bluetoothAdapter?.bluetoothLeScanner?.startScan(bleScanCallback)
        }
        else -> {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), RequestCode.REQUEST_ACCESS_FINE_LOCATION_PERMISSION)
        }
    }
}
r