首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果应用程序关闭,如何在我的颤振应用程序中设置背景位置更新?

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

Stack Overflow用户
提问于 2022-05-09 11:38:33
回答 1查看 949关注 0票数 0

我想添加后台定位服务功能到我的颤音应用程序。

我想得到位置更新在特定的时间间隔,我必须发送位置更新的纬度和经度每N分钟,所以我如何可以这样做,如果应用程序是关闭的,打开的,或在后台?

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

EN

Stack Overflow用户

发布于 2022-05-09 11:50:21

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

代码语言:javascript
复制
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,
            ));
          }
        });
      }
    });
  }
}

用户位置模型:

代码语言:javascript
复制
class UserLocation {
  final double latitude;
  final double longitude;
  final double heading;
  UserLocation({required this.heading, required this.latitude, required this.longitude});
}

然后在页面/查看init函数中,启动一个计时器并将位置更新到您使用的位置API或Firebase。

代码语言:javascript
复制
Timer? locationUpdateTimer;

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

如果您没有使用计时器,请记住释放它。

这将更新位置时,每60秒,当应用程序运行或背景。当应用程序终止时更新位置有点复杂,但是有一个包将每15秒唤醒一次您的应用程序。您可以从以下链接了解如何实现这一目标的文档:

https://pub.dev/packages/background_fetch

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72171370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档