背景
基于公司业务,APP 需要集成蓝牙的扫描,连接,订阅通知等。
遇到问题
码好代码,运行,发现蓝牙始终徘徊在
扫描 > 扫描结束 (timeout)
各种查阅资料后,找到根本原因:
android 6.0之后要用蓝牙还需要添加一个模糊定位的权限
1 | android.permission.ACCESS_COARSE_LOCATION |
Google 官方文档这样描述
Access to Hardware Identifier
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00
To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions:
WifiManager.getScanResults()
BluetoothDevice.ACTION_FOUND
BluetoothLeScanner.startScan()
Note: When a device running Android 6.0 (API level 23) initiates a background Wi-Fi or Bluetooth scan, the operation is visible to external devices as originating from a randomized MAC address.
解决问题
只需要在扫描 BLE 设备之前动态向用户申请位置权限
我的代码:
1 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时 |
结果
问题解决。