【问题标题】:Fetch location from android in background in flutter在颤动的背景中从android中获取位置
【发布时间】:2020-02-27 20:47:03
【问题描述】:

我正在使用下面的代码来跟踪用户的位置。 当我的应用程序在前台时,这可以正常工作。但是当我的应用程序移到后台时它停止工作并且我无法获得任何位置。

import 'dart:async';
import 'package:permission_handler/permission_handler.dart';
import 'package:geolocator/geolocator.dart';

class FetchLocation   {
  var geolocator = Geolocator();
  var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10,forceAndroidLocationManager: true,timeInterval: 1);
  void trackGeoLocation()async{
    final PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.location);
      if(permission == PermissionStatus.granted){
        fetchLocation();
      }else{
        askPermission();
      }

  }
  void askPermission() {
    PermissionHandler().requestPermissions([PermissionGroup.locationAlways]).then(__onStatusRequested);
  }
  void __onStatusRequested(Map<PermissionGroup, PermissionStatus> statuses){
    final status = statuses[PermissionGroup.locationWhenInUse];

    print(status);
    if(status == PermissionStatus.restricted || status == PermissionStatus.neverAskAgain){
    } else if(status == PermissionStatus.denied){
      askPermission();
    }else{
      fetchLocation();
    }
  }
  void fetchLocation(){
    StreamSubscription<Position> positionStream = geolocator.getPositionStream(locationOptions).listen(
            (Position position) {
          print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
        });
  }
}

【问题讨论】:

标签: android flutter geolocation android-background


【解决方案1】:

您可能受到 Android 8 (API 26) 带来的限制的阻碍,这些限制限制了后台应用程序检索当前位置的频率。

这是为了节省电池电量而引入的,但这意味着您需要有一个可见的通知,以便 Android 将应用程序视为处于前台。否则,它只会在应用处于后台时每小时检索几次位置。

https://developer.android.com/about/versions/oreo/background-location-limits 为您提供更多背景信息(请原谅双关语)。

【讨论】:

  • SimonH 谢谢你的回答。是的,它在后台被调用,但它在 10-15 分钟后偶尔被调用。我想像优步应用一样持续跟踪位置。
  • 您需要做一些事情让操作系统认为应用程序在前台(如可见通知)或在服务中运行它。我确信谷歌是你的朋友。 (我删除了我放在这里的链接,因为它有点过时了)
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 2021-12-11
  • 1970-01-01
  • 2020-09-27
相关资源
最近更新 更多