【发布时间】:2016-08-02 16:27:47
【问题描述】:
如何使用react-native-ble-manager 获取可用蓝牙设备的列表?
【问题讨论】:
标签: javascript bluetooth react-native bluetooth-lowenergy
如何使用react-native-ble-manager 获取可用蓝牙设备的列表?
【问题讨论】:
标签: javascript bluetooth react-native bluetooth-lowenergy
我最近不得不使用这个库,这对我有用:
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);
}
编辑:不要忘记请求位置许可!
【讨论】:
首先你应该:
import BleManager from 'react-native-ble-manager';
别忘了:
import { NativeAppEventEmitter } from 'react-native'
然后,在你的组件内部(我在 componentDidMount 上做):
2.1。在'BleManagerDiscoverPeripheral' 事件上为NativeAppEventEmitter 添加句柄:
NativeAppEventEmitter.addListener('BleManagerDiscoverPeripheral',(data) =>
{
console.log(data) // Name of peripheral device
});
2.2。启动您的 BleManager 管理器:
BleManager.start({showAlert: false});
2.3。 BleManager.scan([], 30) 其中第一个值是服务 UUID 的数组,第二个是扫描将运行多长时间的秒数
你可以在官方lib的页面react-native-ble-manager找到原始示例
【讨论】:
要扫描附近的设备,请使用以下代码,
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 上运行您的应用程序,请确保您已为您的应用程序授予位置权限
【讨论】: