I have been working on a react native application where I have to fetch the geolocation at an interval of 10secs and update it to a server. I was able to do the same when the emulator was active/ in the foreground.
However, when the app is minimized, it doesn’t work. I tried using expo task manager but the function doesn’t seem to run when backgrounded.
What is the error here? I have attached my code and output.
I am using android 11 using an emulator and personal device, expo-cli: 3.28.1, sdk: 37.0.12
Here is my code:
import * as Permissions from 'expo-permissions';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
//Navigator
import Navigator from './routing/Routing';
const Main = () => {
const [gpsLatitude, setgpsLatitude] = useState(null);
const [gpsLongitude, setgpsLongitude] = useState(null);
const [batteryLevel, setBatteryLevel] = useState(null);
useEffect(() => {
(async () => await _askForLocationPermission())();
const interval = setInterval(() => {
uploadDataAtInterval();
}, 10000);
return () => clearInterval(interval);
});
const backgroundLocationFetch = async () => {
const { status } = await Location.requestPermissionsAsync();
if (status === 'granted') {
console.log('cmon dance with me!')
await Location.startLocationUpdatesAsync('FetchLocationInBackground', {
accuracy: Location.Accuracy.Balanced,
timeInterval: 10000,
distanceInterval: 1,
foregroundService: {
notificationTitle: 'Live Tracker',
notificationBody: 'Live Tracker is on.'
}
});
}
}
const _askForLocationPermission = async () => {
(async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setgpsErrorMsg('Permission to access location was denied');
}
})();
};
const uploadDataAtInterval = async () => {
console.log('upload using axios');
}
const getGPSPosition = async () => {
let location = await Location.getCurrentPositionAsync({accuracy:Location.Accuracy.High});
setgpsLatitude(location.coords.latitude);
setgpsLongitude(location.coords.longitude);
}
backgroundLocationFetch();
return(
<Navigator />
)
};
TaskManager.defineTask('FetchLocationInBackground', ({ data, error }) => {
if (error) {
console.log("Error bg", error)
return;
}
if (data) {
const { locations } = data;
console.log("BGGGG->", locations[0].coords.latitude, locations[0].coords.longitude);
}
});
export default Main;
Output:
BGGGG 12.88375 80.08169
BGGGG 12.88375 80.08169
App: Not logged on now false //at every 10secs
App: Not logged on now false
App: Not logged on now false
App: Not logged on now false
App: Not logged on now false
App: Not logged on now false