【发布时间】:2022-07-17 12:21:37
【问题描述】:
我想为我的 Flutter App 添加后台定位服务功能。
我想在特定时间间隔获取位置更新,我必须每 N 分钟发送一次位置更新纬度和经度,所以如果应用程序关闭或打开或在后台,我该怎么做?
我需要发送位置更新详细信息以调用 API。 那么请帮助我如何做到这一点以及我应该使用什么包?
【问题讨论】:
标签: flutter
我想为我的 Flutter App 添加后台定位服务功能。
我想在特定时间间隔获取位置更新,我必须每 N 分钟发送一次位置更新纬度和经度,所以如果应用程序关闭或打开或在后台,我该怎么做?
我需要发送位置更新详细信息以调用 API。 那么请帮助我如何做到这一点以及我应该使用什么包?
【问题讨论】:
标签: flutter
在您的应用中创建服务。您可以使用以下代码进行定位服务。
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 秒唤醒你的应用程序。您可以通过以下链接查看有关如何实现此目的的文档:
【讨论】: