You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用后台位置追踪停止问题求解决方案

实现Flutter应用前后台持续位置追踪

针对你的零工招聘门户应用需要在用户班次前1小时持续追踪位置的需求,以下是解决前后台及应用终止状态下位置追踪的具体方案:

1. 升级位置权限

当前代码仅请求locationWhenInUse权限,该权限仅允许前台追踪。要实现后台追踪,需申请始终允许位置权限:

修改权限请求代码

void requestLocationPermission() async {
  // 请求始终允许位置权限(覆盖前台权限)
  PermissionStatus permissionStatus = await Permission.locationAlways.request();
  if (permissionStatus == PermissionStatus.granted) {
    setState(() {
      permissionGranted = true;
    });
  } else {
    setState(() {
      permissionGranted = false;
    });
    // 提示用户前往设置开启权限
    openAppSettings();
  }
}

Future<bool> isPermissionGranted() async {
  return await Permission.locationAlways.isGranted;
}

2. 配置平台特定的后台追踪支持

Android 配置

在android/app/src/main/AndroidManifest.xml中添加以下权限和配置:

<!-- 后台位置权限 -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- 前台服务权限(Android 10+ 必需) -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />

<application ...>
  <!-- 声明位置服务为前台服务 -->
  <service
      android:name="com.lyokone.location.LocationService"
      android:foregroundServiceType="location" />
</application>

iOS 配置

在ios/Runner/Info.plist中添加权限描述:

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>需要始终访问位置以追踪您的班次位置</string>
<key>NSLocationBackgroundUsageDescription</key>
<string>后台追踪位置以确保您能按时到达工作岗位</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要访问位置以追踪您的班次位置</string>

3. 启用后台位置追踪

修改你的startTracking方法,配置location包的后台模式:

void startTracking() async {
  if (!(await isGpsEnabled())) {
    return;
  }
  if (!(await isPermissionGranted())) {
    return;
  }

  // 配置后台追踪选项
  await location.enableBackgroundMode(enable: true);
  
  // 设置位置更新参数(根据需求调整间隔和精度)
  await location.changeSettings(
    accuracy: l.LocationAccuracy.high,
    interval: 30000, // 30秒更新一次
    distanceFilter: 10, // 移动10米才更新
    foregroundNotificationConfig: const l.ForegroundNotificationConfig(
      notificationText: "正在追踪您的位置",
      notificationTitle: "班次位置追踪",
      enableWakeLock: true,
    ),
  );

  subscription = location.onLocationChanged.listen((event) {
    addLocation(event);
    addLocationToFirestore(event);
    log('Location update: ${event.latitude}, ${event.longitude}');
  });
  setState(() {
    trackingEnabled = true;
  });
}

4. 处理应用终止状态

你提到使用alarm包唤醒应用,在闹钟触发时重新启动位置追踪:

闹钟触发后的操作

在闹钟回调中,初始化位置服务并启动追踪:

void onAlarmTrigger() async {
  await Firebase.initializeApp();
  l.Location location = l.Location();
  
  // 检查权限和GPS状态
  bool hasPermission = await Permission.locationAlways.isGranted;
  bool gpsEnabled = await location.serviceEnabled();
  
  if (hasPermission && gpsEnabled) {
    await location.enableBackgroundMode(enable: true);
    location.onLocationChanged.listen((event) {
      addLocationToFirestore(event); // 直接保存到Firestore
      log('Terminated state location update: ${event.latitude}, ${event.longitude}');
    });
  }
}

关键注意事项

  • 电池优化:引导用户将应用从电池优化列表中排除,否则后台追踪可能被系统终止。
  • 更新频率:合理设置位置更新间隔和距离过滤,避免过度消耗电池。
  • iOS 限制:iOS对后台位置追踪有严格限制,仅在必要时启用,且需向用户说明用途以通过App Store审核。

内容的提问来源于stack exchange,提问作者Muhammad Asfar Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:23:09