java - 将目标 SDK 从 28 更改为 29 导致 BLE 扫描不起作用
问题描述
我正在开发需要连接到 BLE 设备的 Android 应用程序。该应用程序按预期工作,但现在当我将目标 SDK 更改为 29(以前是 API 28)时,应用程序停止获得任何扫描结果。在应用程序启动时的 API 级别 28 上,我检查权限。如果没有被批准,我会要求它,然后像往常一样开始扫描 BLE 设备。然后我得到扫描结果,其中包括我周围的 BLE 设备。我通过打印日志消息来确认这一点。现在,当我将目标 SDK 更改为 29(Play 商店需要更新应用程序)时,应用程序停止获取扫描结果。我也没有在日志中收到消息。
使用 API 28 而不是 API 29 的设备:三星 S10 和 Android 10。
我在清单中添加的权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- If your app targets Android 9 or lower, you can declare
ACCESS_COARSE_LOCATION instead. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
我在运行时向用户请求的权限:
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
//here code for asking permission from user.
ActivityCompat.requestPermissions(MainActivity.this,
new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
REQUEST_ENABLE_LOCATION);
}
我与扫描结果交互的代码:
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
String deviceName = device.getName();
if (deviceName != null) {
if (checkdevicename(deviceName)){
Log.d(TAG, "Connect:" + deviceName);
isConnected = true;
mDevice = device;
// // connecting to device. establishing gatt connection.
device.connectGatt(ma,false,mGattCallback);
stopScan();
} else {
Log.d(TAG,"DEVICE NAME =====>"+deviceName);
}
// super.onScanResult(callbackType, result);
}}
解决方案
似乎 SDK 29 中的隐私设置变得更加严格:https ://developer.android.com/about/versions/10/privacy/changes for using BLE(Bluetooth Low Energy)。因此,有了这些知识,您可能需要更新您的权限,请参阅低功耗蓝牙扫描失败。
简而言之(根据 29 中的隐私版本更改)您需要使用ACCESS_FINE_LOCATION
权限才能使用某些蓝牙功能(以及 WiFi 等)。
某些电话、蓝牙、Wi-Fi API 需要 FINE 位置权限如果您的应用面向 Android 10 或更高版本,则它必须具有 ACCESS_FINE_LOCATION 权限才能使用 Wi-Fi、Wi-Fi Aware 或蓝牙 API 中的多种方法。
推荐阅读
- python - How to pass functions with arguments as parameter to another function in python with function name as a string?
- python - 如何在 python 中使用 ElementTree 将 xml 元素作为具有命名空间的字符串?
- jquery - jQuery - 仅当锚点 href 仅包含 URL 时才返回 true
- java - Android - 获取主机不会持续返回
- c# - 从 Azure 表存储中检索行
- javascript - 简化画布上的颜色
- angular - 当我在 Firebase 上部署 Angular 5 应用程序时,API 被阻止
- loops - Common Lisp dotimes 结果之谜
- reactjs - TypeScript React SFC children props type error
- android - 3 Admobs apps, 1 of which keeps failing on load with error code 3