因为我将有多个应用程序使用相同的实现来连接到 BLE 设备,所以我尝试将该代码移动到模块内。然而,我遇到了一个奇怪的问题,当相同的代码在应用程序内的文件夹内工作时,扫描代码在模块内不起作用。
我已经使用以下代码进行了测试:
import {
BleError,
BleManager,
Device as BlxDevice,
LogLevel,
} from 'react-native-ble-plx';
import { PermissionsAndroid } from 'react-native';
const manager = new BleManager();
manager.setLogLevel(LogLevel.Verbose);
export const tryScan = () => {
console.log('In main app');
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
),
manager.startDeviceScan(
null,
{ allowDuplicates: true },
(error: BleError | null, scannedDevice: BlxDevice | null) => {
console.log('Discovered device', scannedDevice);
manager.stopDeviceScan();
},
);
};
当在模块内部时,根本没有发现任何设备,当在应用程序中不作为模块时,它按预期工作。
该模块具有本机库作为对等依赖项:
"peerDependencies": {
"react-native": "^0.64.x",
"react-native-ble-plx": "^2.x"
},
应用程序以这种方式包含模块
"dependencies": {
"device-control": "file:../device-control",
},
我已验证我在应用程序的 node_modules 中拥有正确的代码。
让我更加困惑的是,在使用react-native-ble-plx的应用程序中,可以使用
manager.onStateChange
来监控BLE状态。
我在logcat中没有发现错误,在metro中也没有发现错误。谁能告诉我错误的原因是什么?
我也面临着同样的问题。除非您不需要编译 SDK,否则我确实从
33
下载了它到 31
。同时降级目标 SDK。我尚未测试不同的配置,但此配置适用于我的原型项目。
buildToolsVersion = "29.0.3"
minSdkVersion = 23
compileSdkVersion = 31
targetSdkVersion = 30
我请求这些权限:
const _PERMISSIONS = [
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT
];
if (Platform.OS != "android") return;
const granted = await PermissionsAndroid.requestMultiple(_PERMISSIONS);
AndroidManifest.xml
<!-- Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in
Android API 23+ -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
我在 IOS 上也遇到了同样的问题。有没有人想出解决办法? 我正在使用:
"react-native": "0.74.2",
"react-native-ble-plx": "^3.2.0",
我的 info.plist 包含:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>We need access to Bluetooth to connect to nearby devices.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need access to Bluetooth to connect to nearby devices.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to scan for Bluetooth devices.</string>
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>bluetooth-peripheral</string>
<string>external-accessory</string>
<string>fetch</string>
<string>processing</string>
</array>