首页 > 解决方案 > 在蓝牙关闭的情况下识别 Android / Kotlin 上的 BLE 设备

问题描述

我正在开发一种检查 BLE 设备的解决方案,并使用 Android 附带的本机 API 来检查 BluetoothLeScanner。

想了解更好的操作,我拿了位置许可和蓝牙。

扫描开始后,我将手机上的蓝牙关闭,Moto G2 Android 6.0当我在 a 上测试时,扫描仍然给我预期的结果,Samsung S8 Android 9并且Sony Xperia T2 Ultra Android 5.1在我得到的日志中,蓝牙被禁用并且扫描已停止。

我只能在购买时进行测试,如下所示

 bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
 bluetoothAdapter = bluetoothManager.adapter

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            bluetoothScanner = bluetoothAdapter.bluetoothLeScanner
        }

@TargetApi(Build.VERSION_CODES.M)
    class BleScanCallback(resultMap: MutableMap) : ScanCallback() {

var resultOfScan = resultMap @RequiresApi(Build.VERSION_CODES.LOLLIPOP) @TargetApi(Build.VERSION_CODES.M) override fun onScanResult(callbackType: Int, result: ScanResult?) { addScanResult(result) Log.v("Main Activity", "I found a ble device ${result}") Log.v("Main Activity", "I found a ble device ${result?.device?.address}") } override fun onBatchScanResults(results: MutableList<ScanResult>?) { results?.forEach { result -> addScanResult(result) } } override fun onScanFailed(errorCode: Int) { Log.v("Main Activity","Bluetooth LE scan failed. Error code: $errorCode") } fun addScanResult(scanResult: ScanResult?) { val bleDevice = scanResult?.device val deviceAddress = bleDevice?.address resultOfScan.put(deviceAddress, bleDevice) }

当蓝牙在线时,scanResult会带来必要的信息,我已经将其设置为下图

https://i.stack.imgur.com/o9jGRm.png

我看到这使扫描变得更糟

标签: androidkotlinbluetooth-lowenergybeacon

解决方案


蓝牙关闭时无法检测 BLE 设备

必须启用蓝牙

设置 BLE

在您的应用程序可以通过 BLE 进行通信之前,您需要验证设备是否支持 BLE,如果支持,请确保它已启用。


推荐阅读