【问题标题】:How to set Background Location update In my Flutter App also if App is Closed?如果应用程序已关闭,如何在我的 Flutter 应用程序中设置后台位置更新?
【发布时间】:2022-07-17 12:21:37
【问题描述】:

我想为我的 Flutter App 添加后台定位服务功能。

我想在特定时间间隔获取位置更新,我必须每 N 分钟发送一次位置更新纬度和经度,所以如果应用程序关闭或打开或在后台,我该怎么做?

我需要发送位置更新详细信息以调用 API。 那么请帮助我如何做到这一点以及我应该使用什么包?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    在您的应用中创建服务。您可以使用以下代码进行定位服务。

    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

    【讨论】:

    • 我使用 geolocator 包通过我的函数获取了位置详细信息,但现在如果应用程序关闭,我如何调用此函数?请给我 background_fetch 示例
    • 用户位置详情请在此处添加
    • @krishna 添加了用户位置模型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多