简体   繁体   English

在颤动的背景中从android获取位置

[英]Fetch location from android in background in flutter

I am using below code to get the track the location of user.我正在使用下面的代码来跟踪用户的位置。 This works proper when my application in foreground.当我的应用程序在前台时,这可以正常工作。 But when my application move to background it stop working and i can not get any location.但是当我的应用程序移到后台时它停止工作并且我无法获得任何位置。

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

You are probably being hampered by the restrictions brought in with Android 8 (API 26) which limits the frequency that background apps can retrieve the current location.您可能受到 Android 8 (API 26) 带来的限制的阻碍,这些限制限制了后台应用程序可以检索当前位置的频率。

This was brought in to save battery but it means that you will need to have a visible notification in order for Android to consider the app as being in the foreground.这样做是为了节省电池,但这意味着您需要有一个可见的通知,以便 Android 将应用程序视为处于前台。 Otherwise it will only retrieve the location a few times per hour whilst the app is in the background.否则,当应用程序在后台时,它每小时只会检索几次位置。

https://developer.android.com/about/versions/oreo/background-location-limits gives you some further background (excuse the pun) information. https://developer.android.com/about/versions/oreo/background-location-limits为您提供了一些进一步的背景信息(请原谅双关语)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM