如何使用 react-native-ble-manager 获取可用蓝牙设备的列表? ?
最佳答案
我最近不得不使用这个库,这对我有用:
import { NativeModules, NativeEventEmitter } from 'react-native';
import BleManager from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
...
state = {
peripherals: new Map(),
};
componentDidMount() {
BleManager.start({ showAlert: false })
this.handlerDiscover = bleManagerEmitter.addListener(
'BleManagerDiscoverPeripheral',
this.handleDiscoverPeripheral
);
this.handlerStop = bleManagerEmitter.addListener(
'BleManagerStopScan',
this.handleStopScan
);
this.scanForDevices(); // I chose to start scanning for devices here
}
scanForDevices() {
BleManager.scan([], 15);
}
handleDiscoverPeripheral = (peripheral) => {
const { peripherals } = this.state;
if (peripheral.name) {
peripherals.set(peripheral.id, peripheral.name);
}
this.setState({ peripherals });
};
handleStopScan = () => {
console.log('Scan is stopped. Devices: ', this.state.peripherals);
}
编辑:不要忘记请求位置许可!
关于javascript - 使用 react-native-ble-manager 获取可用蓝牙设备的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38725885/