我正在开发需要连接到 BLE 设备的 Android 应用程序。 该应用程序按预期工作,但现在当我将目标 SDK 更改为 29(以前是 API 28)时,应用程序将停止获取任何扫描结果。 在 API 级别 28,当应用程序启动时,我检查权限。如果未获批准,我会请求它,然后像往常一样开始扫描 BLE 设备。然后我得到扫描结果,其中包括我周围的 BLE 设备。我通过打印日志消息来确认这一点。 现在,当我将目标 SDK 更改为 29(Play 商店更新应用程序所需的值)时,应用程序将停止获取扫描结果。我也没有在日志中收到消息。
使用 API 28 但不使用 API 29 的设备:搭载 Android 10 的 Samsung S10。
我在 list 中添加的权限
<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用于使用 BLE(低功耗蓝牙)。 因此,有了这些知识,您可能需要更新您的权限,请参阅 Scanning of Bluetooth Low Energy Fails也是如此。
简而言之(根据29年隐私版本的变化)你需要使用ACCESS_FINE_LOCATION
允许使用某些蓝牙功能(以及 WiFi 等)。
Some telephony, Bluetooth, Wi-Fi APIs require FINE location permission If your app targets Android 10 or higher, it must have the ACCESS_FINE_LOCATION permission in order to use several methods within the Wi-Fi, Wi-Fi Aware, or Bluetooth APIs.
关于java - 将目标 SDK 从 28 更改为 29 导致 BLE 扫描不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63933347/