如何使用 react-native-ble-manager 获取可用蓝牙设备列表?
First you should:
import BleManager from 'react-native-ble-manager';
and don't forget:
import { NativeAppEventEmitter } from 'react-native'
Then, inside of your component (I'm doing on componentDidMount
):
2.1. Add Handle to NativeAppEventEmitter
on 'BleManagerDiscoverPeripheral'
event:
NativeAppEventEmitter.addListener('BleManagerDiscoverPeripheral',(data) =>
{
console.log(data) // Name of peripheral device
});
2.2. Start your BleManager manager:
BleManager.start({showAlert: false});
2.3. BleManager.scan([], 30)
where first value is an array if service UUID, second is seconds how long scan will run
最近我不得不使用这个库,以下是我的解决方法:
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);
}
编辑:别忘了请求位置权限!
使用以下代码扫描附近的设备:
scanNearByDevices(serviceUUIDList, duration, isAllowDuplicates) {
bleManager
.scan(serviceUUIDList, duration, isAllowDuplicates)
.then(results => {
console.log('Scanning...');
// this.setState({scanning: true});
});
}
然后使用以下代码获取发现设备列表:
getDiscoverdDevices() {
return new Promise((resolve, reject) => {
bleManager
.getDiscoveredPeripherals()
.then(devices => {
console.log('Discovered devices:', devices);
this.deviceMap.set(device.id, device);
}
resolve(devices);
})
.catch(error => {
console.log('error fail: ', error);
reject(error);
});
});
}
如果您正在运行Android应用程序,请确保已向您的应用程序授予位置权限