can't make background mode work
See original GitHub issueMy app is supposed to send a message to a specific BLE device when that device is in range. Ideally this should work even when the app is closed/in background mode. I used the simplest restoreStateFunction
I could think of: it just makes a fetch
request to an endpoint on my server. However, this is never called once the app goes to background. I created a sample repo to quickly replicate the problem, and here’s the relevant code. Tested on android/ios, debug/release and nothing works. Any idea about what I’m doing wrong?
Also, I only want the app to be turned on only if a specific device is in range, and I see this is configured only in startDeviceScan
. Will the background mode take this into account, or the app will be turned on anytime a new ble device is in range?
import React from 'react';
import {BleManager} from "react-native-ble-plx";
import {PermissionsAndroid, Platform} from 'react-native';
export class BleComponent extends React.PureComponent {
constructor() {
super();
if (Platform.OS === 'android') {
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION)
.then(granted => {
if (granted !== 'granted') {
console.log('BLUETOOTH denied')
}
else {
this.initializeManager();
}
})
} else {
this.initializeManager();
}
}
initializeManager() {
this.manager = new BleManager({
restoreStateIdentifier: 'testBleBackgroundMode',
restoreStateFunction: bleRestoredState => {
fetch('http://restoreStateFunctionWasCalled.com')
}
});
const subscription = this.manager.onStateChange((state) => {
if (state === 'PoweredOn') {
this.scanAndConnect();
}
}, true);
}
scanAndConnect() {
console.log(('scan and connect'));
this.manager.startDeviceScan(["0000fefb-0000-1000-8000-00805f9b34fb"], null, (error, device) => {
if (error) {
console.log(("BLE error"));
return
}
console.log(device);
});
}
render() {
return null;
}
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:17 (2 by maintainers)
Top GitHub Comments
@7772 It’s great to hear form you that it’s worked. Even to put correct serviceUUID it doesn’t work. Can you please make a proper documentation on background mode os scan and can share, I think it will be help ful for lot of people. That will be grateful though 😃 Or someone can say it never work 😦
I have trouble on scanning device on background, but solved it.
startDeviceScan
I noticed what I should do after reading on this