I want to capture current location for every 15 min and send that location to server.
I used react-native-background-geolocation. It works only in foreground for me but
not in background. Here is my code
const [enabled, setEnabled] = React.useState(true);
const [location, setLocation] = React.useState('');
React.useEffect(() => {
/// 1. Subscribe to events.
const onLocation = BackgroundGeolocation.onLocation(location => {
console.log('[onLocation]', location);
setLocation(JSON.stringify(location, null, 2)) });
BackgroundGeolocation.ready({
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 10,
stopTimeout: 5,
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app.
startOnBoot: true, // <-- Auto start tracking when device is powered-up.
batchSync: false, // <-- [Default: false] Set true to sync locations to server in
autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives.
headers: {
'X-FOO': 'bar',
},
params: {
auth_token: 'maybe_your_server_authenticates_via_token_YES?',
},
}).then(state => {
setEnabled(state.enabled);
BackgroundGeolocation.watchPosition(
function (location) {
console.log('- Watch position: ', location);
fetch('https://shopql.herokuapp.com/shop', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({location}),
}).then(data => {
console.log('Api called');
});
},
function (errorCode) {
alert('An location error occurred: ' + errorCode);
},
{
interval: 900000, // <-- retrieve a location every 15 min.
},
);
if (!state.enabled) {
BackgroundGeolocation.start(function () {
console.log('- Start success');
});
}
console.log(
'- BackgroundGeolocation is configured and ready: ',
state.enabled,
);
});
return () => {
onLocation.remove();
onActivityChange.remove();
onProviderChange.remove();
};
}, []);
React.useEffect(() => {
if (enabled) {
BackgroundGeolocation.stop();
setLocation('');
}
}, [enabled]);
I tried with this code but this code is not working for me. it works fine in foreground but not working when app closed. Please help me on how to update current location when app closed