https://kotlinlang.org logo
Title
s

Shawn Karber_

05/04/2020, 10:47 PM
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

Matt Lien

05/05/2020, 1:14 AM
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:
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

rahul_lohra

05/06/2020, 10:03 AM