react-native-background-timer icon indicating copy to clipboard operation
react-native-background-timer copied to clipboard

Bluetooth Scanning not working in background

Open rgstephens opened this issue 7 years ago • 3 comments

I created a sample Android app here that calls BackgroundTimer.setInterval with a 10 second interval. Each interval it writes a timestamp to a Redux store and also calls the react-native-ble-plx bluetooth library to scan for devices for 2 seconds, writing the list of devices to Redux which is displayed by the main component.

When the app loses focus, the timestamps continue to be written to the Redux store but the scanning no longer works. Log messages for the scanning show it starting every 10 seconds and stopping after the 2 second setTimeout but no devices are found when the app is in the background.

index.js

  const intervalId = BackgroundTimer.setInterval(() => {
    console.log("*** index.js setInterval", new Date());
    store.dispatch({ type: "TIMESTAMP" });
    doScan(scanLength);
  }, scanInterval);

doScan

export function doScan(scanTime) {
  let deviceList = [];
  if (!bleManager) {
    console.log('--- first scanning call, instantiate new BleManager');
    bleManager = new BleManager({
      restoreStateIdentifier: 'foregroundTest',
      restoreStateFunction: (bleRestoredState) => {
        console.log('restoreStateFunction called');
      },
    });
  }

  // Set timer to stop scan
  setTimeout(function() {
    console.log('<<< stopping scan, ', new Date());
    if (bleManager) {
      bleManager.stopDeviceScan();
    }
  }, scanTime);

  // Start scan
  bleManager.startDeviceScan(null, null, (error, device) => {
    if (error) {
      // Handle error (scanning will be stopped automatically)
      console.log('bleScan error, stopping - ', error);
      return;
    }
    if (!deviceList.includes(device.id)) {
      console.log('add device:', device.id, ', deviceList:', deviceList);
      deviceList.push(device.id);  
      store.dispatch({ type: 'DEVICE', device: device });
    }
  });
}

rgstephens avatar Feb 13 '18 04:02 rgstephens

Hey, I am facing the same issue. Any lucks?

terfender avatar May 03 '18 23:05 terfender

Also trying to do the exact same thing. Any guidance? @Terfender @rgstephens

KaneLabs avatar Sep 19 '19 14:09 KaneLabs

I gave up on this.

rgstephens avatar Sep 19 '19 15:09 rgstephens