I have been working on a team developing an app in Flutter. We need to track the distance travelled using the GPS but the challenge is that Flutter no longer allows both foreground and background location tracking (even with a coarse level of accuracy).
Based on a review of the latest Google guidelines, it seems like Google should allow our app to track the device when it’s in the background, but it does not. In fact, turning on foreground and background location services seemed to be working a month or two back. We have tried both the location and geolocation packages, to no avail. Either of them immediately stops tracking when the app is in the background and we get one big jump in location when the app is returned to the foreground.
Here’s what we’ve tried
AndroidManifest.xml
...
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
...
App Code Using Geolocation
...
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
//Permission returns denied Location
//this is due to the background permission in the android manifest
//turn off background permission and the permission is allowed
if (permission == LocationPermission.deniedForever)
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
...
App Code Using Location
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
print('Service could not be enabled');
return false;
}
// This code throws and exception even if I respond to the
// Google prompts and I select allow location service and all the time access
try {
await location.enableBackgroundMode(enable: true);
} catch(error) {
print("Can't set background mode");
}
Any guidance for how to achieve this would be much appreciated.