在flutter中从android中获取位置信息 [英] Fetch location from android in background in flutter

查看:82
本文介绍了在flutter中从android中获取位置信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您可能会受到Android 8(API 26)带来的限制的限制,该限制限制了后台应用程序可以检索当前位置的频率.

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才能认为该应用程序位于前台.否则,在后台运行该应用程序时,每小时只会检索几次该位置.

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. 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 为您提供了一些其他背景信息(例如,双关语).

https://developer.android.com/about/versions/oreo/background-location-limits gives you some further background (excuse the pun) information.

这篇关于在flutter中从android中获取位置信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆