我一直在与一个使用Flutter开发应用的团队合作。我们需要使用GPS追踪行驶距离,但挑战在于Flutter不再允许前景和后台位置跟踪(即使使用粗略的精度级别)。
根据最新的Google指南审查,看起来Google应该允许我们的应用在后台跟踪设备,但事实并非如此。事实上,启用前景和后台位置服务似乎在一个月或两个月前仍然有效。我们已经尝试了location
和geolocation
包,但没有成功。任何一个在应用处于后台时都会立即停止跟踪,并且当应用回到前台时我们只得到一个位置大的跳变。
以下是我们尝试过的方法
AndroidManifest.xml
...
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
...
应用程序代码使用地理位置
...
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.');
}
...
使用位置的应用代码
_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");
}
任何有关如何实现这一目标的指导都将不胜感激。