如果应用程序关闭,如何在Flutter应用程序中设置后台位置更新?

bsxbgnwa  于 2022-12-19  发布在  Flutter
关注(0)|答案(1)|浏览(142)

我想在Flutter应用中添加后台位置服务功能。
我想在特定的时间间隔获得位置更新,我必须发送位置更新纬度和经度每N分钟,所以我怎么能做到这一点,无论是应用程序关闭或打开或在后台?
我需要发送位置更新细节来调用API。所以请帮助我如何才能做到这一点,我应该使用什么包?

mnemlml8

mnemlml81#

在你的应用中创建服务。你可以使用以下代码提供位置服务。

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});
}

然后在你的页面/视图初始化函数中,启动一个计时器,并将位置更新为你的位置API或Firebase。

Timer? locationUpdateTimer;

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

如果不使用计时器,请记住将其丢弃。
这将在应用程序运行或后台运行时每60秒更新一次位置。在应用程序终止时更新位置有点复杂,但有一个软件包会每15秒唤醒一次应用程序。您可以通过以下链接查看如何实现此功能的文档:
https://pub.dev/packages/background_fetch

相关问题