如果应用程序关闭,如何在我的Flutter应用程序中设置背景位置更新?



我想添加后台位置服务功能到我的Flutter应用程序。

我想在特定的时间间隔获得位置更新,我必须发送位置更新纬度和经度每N分钟那么我怎么能做到这一点,如果应用程序是关闭或打开或在后台?

我需要发送位置更新细节来调用API。那么,请告诉我如何做到这一点,我应该使用什么软件包?

在你的应用程序中创建一个服务。你可以使用下面的代码为位置服务。

import 'package:location/location.dart';
class LocationService {
UserLocation _currentLocation;
var location = Location();
//One off location
Future<UserLocation> getLocation() async {
try {
var userLocation = await location.getLocation();
_currentLocation = UserLocation(
latitude: userLocation.latitude,
longitude: userLocation.longitude,
);
} on Exception catch (e) {
print('Could not get location: ${e.toString()}');
}
return _currentLocation;
}
//Stream that emits all user location updates to you
StreamController<UserLocation> _locationController =
StreamController<UserLocation>();
Stream<UserLocation> get locationStream => _locationController.stream;
LocationService() {
// Request permission to use location
location.requestPermission().then((granted) {
if (granted) {
// If granted listen to the onLocationChanged stream and emit over our controller
location.onLocationChanged().listen((locationData) {
if (locationData != null) {
_locationController.add(UserLocation(
latitude: locationData.latitude,
longitude: locationData.longitude,
));
}
});
}
});
}
}

用户位置模型:

class UserLocation {
final double latitude;
final double longitude;
final double heading;
UserLocation({required this.heading, required this.latitude, required this.longitude});
}

然后在你的页面/视图init函数中,启动一个计时器并更新位置到你的位置API或Firebase,无论你使用哪个。

Timer? locationUpdateTimer;
locationUpdateTimer = Timer.periodic(const Duration(seconds: 60), (Timer t) {
updateLocationToServer();
});

如果您不使用计时器,请记住处置它。

这将在应用程序运行或后台时每60秒更新一次位置。当应用程序终止时更新位置有点复杂,但有一个包会每15秒唤醒你的应用程序。您可以通过以下链接查看如何实现此功能的文档:

https://pub.dev/packages/background_fetch

相关内容

最新更新