我想添加后台定位服务功能到我的颤音应用程序。
我想得到位置更新在特定的时间间隔,我必须发送位置更新的纬度和经度每N分钟,所以我如何可以这样做,如果应用程序是关闭的,打开的,或在后台?
我需要发送位置更新细节,以调用API。所以,请帮助我如何做到这一点,我应该使用什么包?
发布于 2022-05-09 11:50:21
在应用程序中创建一个服务。您可以为位置服务使用以下代码。
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://stackoverflow.com/questions/72171370
复制相似问题