在 Android / Kotlin 上识别蓝牙关闭的 BLE 设备

identify BLE devices on Android / Kotlin with bluetooth off

我正在开发一个检查 BLE 设备的解决方案,我使用 Android 附带的原生 API 来检查 BluetoothLeScanner。

想了解好一点的操作,我拿了定位权限和蓝牙。

扫描开始后,我将 phone 上的蓝牙关闭,在 Moto G2 Android 6.0 上,当我在 Samsung S8 Android 9 和 [= 上测试时,扫描仍然给我预期的结果14=] 在我得到的日志中,蓝牙已禁用并且扫描已停止。

我购买后只能进行如下测试

 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() {</p>

    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

我看到这使得扫描变得更慢

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

必须启用蓝牙

Set up BLE

Before your application can communicate over BLE, you need to verify that BLE is supported on the device, and if so, ensure that it is enabled.

在某些 Android 设备上,包括 Pixel 手机、Android 一台设备和未修改的 AOSP 版本,在快速设置面板中关闭蓝牙并不会真正关闭蓝牙. 相反,它只是阻止蓝牙连接和软件配对,但允许蓝牙 LE 扫描继续不受影响。正如@Jorgesys 正确指出的那样,如果蓝牙无线电真的关闭,则无法检测到 BLE 设备,所以让我再说一遍:尽管快速设置面板说了什么,但蓝牙不一定关闭。

在支持的设备上,只有满足以下两个条件时才会发生这种情况:

  1. 蓝牙已在完整设置菜单中打开(打开 Android 9:设置 -> 连接的设备 -> 连接首选项 -> 蓝牙打开)
  2. 用户已选择 "Allow apps and services to scan for nearby devices at any time, even when Bluetooth is off. This can be used, for example, to improve location-based features and services."(设置 -> 安全和位置 -> 位置 -> 高级 -> 扫描 -> 蓝牙扫描开启)