首页 > 解决方案 > 我希望我的应用程序充当蓝牙设备,并且应该对具有我的应用程序名称的其他设备可见并与其他设备共享数据

问题描述

我希望我的应用程序充当蓝牙设备,并且应该对具有我的应用程序名称的其他设备可见。为此,我正在使用 react-native-ble-manager。

我还想将数据共享到连接的设备。但是,当我尝试获取连接的外围设备详细信息(例如其名称、id)时,我在控制台日志中没有得到任何信息。使用它的代码是...

    const startScan = () => {

      
      // skip if scan process is currenly happening
      if (isScanning) {
        console.log(isScanning) //true
        console.log('scaning')
        return;
      }
  
      // first, clear existing peripherals
      peripherals.clear();
      setList(Array.from(peripherals.values()));
  
      // then re-scan it
      BleManager.scan([], 30, true)
        .then(() => {
          console.log('Scanning...');
          setIsScanning(true);
        })
        .catch((err) => {
          console.error(err);
        });
        console.log('########################')
       console.log(list)
        console.log(peripherals)
    };

在使用 bleEmitter 调用函数的 useEffect 中。

 BleManager.start({ showAlert: false });

    // add ble listeners on mount
     bleEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
     bleEmitter.addListener('BleManagerStopScan', handleStopScan);
    // bleEmitter.addListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral);
    // bleEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic);

    // check location permission only for android device
    if (Platform.OS === 'android' && Platform.Version >= 23) {
      PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((r1) => {
        if (r1) {
          console.log('Permission is OK');
          return;
        }

        PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((r2) => {
          if (r2) {
            console.log('User accept');
            return
          }
         console.log('User refuse');
        });
      });
    }

并且 handleDiscoverPeripheral 包含外围的详细信息,代码是......

 const handleDiscoverPeripheral = (peripheral) => {
      console.log('Got ble peripheral', peripheral);
  
      if (!peripheral.name) {
        peripheral.name = 'NO NAME';
      }
  
      peripherals.set(peripheral.id, peripheral);
      setList(Array.from(peripherals.values()));
    };

但是我的代码没有通过这个 handleDiscoverPeripheral 。它直接移动到下一个函数 ishandleStopScan 函数..

而且我也无法获得附近的蓝牙设备列表。

任何人都可以在这种情况下帮助我,我想将数据从我的应用程序发送到我通过蓝牙连接的设备..

标签: androidreact-native-androidreact-native-flatlistreact-native-ble-plxreact-native-ble-manager

解决方案


推荐阅读