I am using below code to get the track the location of user. This works proper when my application in foreground. But when my application move to background it stop working and i can not get any location.
import 'dart:async';
import 'package:permission_handler/permission_handler.dart';
import 'package:geolocator/geolocator.dart';
class FetchLocation {
var geolocator = Geolocator();
var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10,forceAndroidLocationManager: true,timeInterval: 1);
void trackGeoLocation()async{
final PermissionStatus permission = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.location);
if(permission == PermissionStatus.granted){
fetchLocation();
}else{
askPermission();
}
}
void askPermission() {
PermissionHandler().requestPermissions([PermissionGroup.locationAlways]).then(__onStatusRequested);
}
void __onStatusRequested(Map<PermissionGroup, PermissionStatus> statuses){
final status = statuses[PermissionGroup.locationWhenInUse];
print(status);
if(status == PermissionStatus.restricted || status == PermissionStatus.neverAskAgain){
} else if(status == PermissionStatus.denied){
askPermission();
}else{
fetchLocation();
}
}
void fetchLocation(){
StreamSubscription<Position> positionStream = geolocator.getPositionStream(locationOptions).listen(
(Position position) {
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
}
}
You are probably being hampered by the restrictions brought in with Android 8 (API 26) which limits the frequency that background apps can retrieve the current location.
This was brought in to save battery but it means that you will need to have a visible notification in order for Android to consider the app as being in the foreground. Otherwise it will only retrieve the location a few times per hour whilst the app is in the background.
https://developer.android.com/about/versions/oreo/background-location-limits gives you some further background (excuse the pun) information.