我正在使用 Jetpack Compose 构建一个扫描 BLE 设备的应用程序。这是一个可组合项,它在进入组合时简单地扫描 BLE 设备,并在退出时停止扫描。我已经获得BLUETOOTH_CONNECT和BLUETOOTH_SCAN的权限。问题是,当扫描开始时,什么也没有发生。程序没有崩溃,但我也找不到任何 BLE 设备。我注意到 logcat 中出现错误:“uid 1002 进行的错误调用。包“top.frankyang.gc”不属于 uid 1002。”,这与失败有关吗?我该如何解决这个问题或者我的代码有什么问题吗?我正在使用 Android 13,我的程序面向 Android 12。
// when this Composable enters composition, it's certain that we have the permission
@SuppressLint("MissingPermission")
@Composable
fun BleScanner(adapter: BluetoothAdapter) {
val scanner = adapter.bluetoothLeScanner
val devices = remember { mutableStateListOf<BluetoothDevice>() }
val callback = remember {
object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
Log.i(TAG, "onScanResult: new device found: ${result.device}")
devices.add(result.device)
}
override fun onBatchScanResults(results: MutableList<ScanResult>) {
super.onBatchScanResults(results)
Log.i(TAG, "onBatchScanResults: new devices found: $results")
results.mapTo(devices) { it.device }
}
override fun onScanFailed(errorCode: Int) {
Log.w(TAG, "onScanFailed: scan failure: errorCode=$errorCode")
}
}
}
for (device in devices) {
Text(device.name)
}
if (devices.isEmpty()) {
Text(stringResource(R.string.no_device))
}
DisposableEffect(scanner) {
Log.i(TAG, "BleScanner: start scanning for BLE devices")
scanner.startScan(callback)
onDispose {
Log.i(TAG, "BleScanner: scanning stopped or adapter changed")
scanner.stopScan(callback)
}
}
}
2023-12-29 20:58:42.902 25173-25173 Bt top.frankyang.gc I BleScanner: scanning stopped or adapter changed
2023-12-29 20:58:42.903 25173-25173 BluetoothAdapter top.frankyang.gc D isLeEnabled(): ON
2023-12-29 20:58:42.906 25173-25173 BluetoothAdapter top.frankyang.gc D isLeEnabled(): ON
2023-12-29 20:58:43.862 25173-25173 Bt top.frankyang.gc I BleScanner: start scanning for BLE devices
2023-12-29 20:58:43.862 25173-25173 BluetoothAdapter top.frankyang.gc D isLeEnabled(): ON
2023-12-29 20:58:43.866 25173-4472 BluetoothLeScanner top.frankyang.gc D onScannerRegistered() - status=0 scannerId=8 mScannerId=0
2023-12-29 20:58:43.870 2489-4327 AppOps system_server E Bad call made by uid 1002. Package "top.frankyang.gc" does not belong to uid 1002.
在 BLUETOOTH_SCAN 权限声明中添加 android:usesPermissionFlags="neverForLocation" ,如下所示
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
否则扫描器不会给出结果(或者您可以在Manifest.xml中声明位置权限并打开设备位置)。
这样做会给出扫描结果。
注意:
device.name
可能会导致NPE