Bluetooth Scanning not working in background
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 });
}
});
}
Hey, I am facing the same issue. Any lucks?
Also trying to do the exact same thing. Any guidance? @Terfender @rgstephens
I gave up on this.