javascript - 使用 react-native-ble-manager 获取可用蓝牙设备的列表

标签 javascript bluetooth react-native bluetooth-lowenergy

如何使用 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/

相关文章:

Javascript:无需 ID 即可获取值

javascript - WordPress 中的内联 SVG 回退

javascript - 如何更改具有指定类的每个 html 元素的值?

android-layout - 原生 UI 组件 - Android View 更新时刷新

ios - IOS(React Native)上的NotificationHub注册问题

javascript - DropDown 组件 CSS 问题

python - PyBluez 导入错误 : DLL load failed: %1 is not a valid Win32 application

android - 将蓝牙配对对话带到前面

iphone - iOS 6 - BluetoothManager 框架 - "NSObject"未找到错误

reactjs - react 'componentWillReceiveProps' 使用