dotintent / react-native-ble-plx

React Native BLE library
Apache License 2.0
3.08k stars 515 forks source link

Question CASE OF USE #1244

Open Beckmann0o opened 1 month ago

Beckmann0o commented 1 month ago

Prerequisites

Question

Hello, good afternoon. Can React Native BLE PLX perform device scans in the background, even if the device screen is off? My intention is to configure a foreground service that calls liberia to scan devices every 30 seconds. I was able to configure the foreground services but it happens to me that when I lock the cell phone the library stops scanning devices, I see the js code of my live app but I don't see devices, this is a limitation of the liberia or is it the operating system that does not allow doing Does it still scan when the screen is locked?

GREETINGS FROM ARGENTINA !!

Question related code

const backgroundTask = async (taskDataArguments) => {
  const { delay } = taskDataArguments;

  while (BackgroundService.isRunning()) {
    await scanForDevice();
    await sleep(delay - 7000); // Esperar el tiempo restante para completar 30 segundos
  }
};

const scanForDevice = async () => {
  const permissionsGranted = await requestPermissions();
  if (!permissionsGranted) {
    console.log("No se otorgaron los permisos necesarios");
    return;
  }

  console.log("INICIANDO ESCANEO");

  bleManager.stopDeviceScan();
  bleManager.startDeviceScan(null, null, (error, device) => {
    if (error) {
      console.error("Error en el escaneo:", error);
      return;
    }
    console.log(device.name);
    if (
      device.name === "W6" &&
      device.serviceData &&
      device.serviceData["0000feab-0000-1000-8000-00805f9b34fb"]
    ) {
      console.log("LO ENCONTRÉ");
      console.log("Detalles del dispositivo:", device);
      Alert.alert("PANICO DETECTADO");
      bleManager.stopDeviceScan();
    }
  });

  // Detener el escaneo después de 30 segundos
  await sleep(7000);
  bleManager.stopDeviceScan();
  console.log("Escaneo Bluetooth detenido");
};