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

React Native安卓真实场景后台定位失效问题求助

React Native Android 12 后台定位失效问题解决

问题场景

使用react-native-geolocation-service和@supersami/rn-foreground-service开发定位类应用,通过Geolocation.watchPosition获取前台位置,定位配置如下:

{ 
  accuracy: { android: 'high', ios: 'best', }, 
  enableHighAccuracy: true, 
  distanceFilter, 
  interval: 5000, 
  fastestInterval: 2000, 
  forceLocationManager: true, 
  showLocationDialog: true, 
  showsBackgroundLocationIndicator: true, 
}
  • 模拟GPS测试:后台运行正常,检查点可正常采集,前台通知能实时更新
  • 真实场景测试(仅Android 12):已授予「始终允许」位置权限,配置了ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION、ACCESS_BACKGROUND_LOCATION权限,但无法触发检查点,通知显示的地理位置无变化
  • 仅当其他应用使用定位功能时,本应用定位才恢复正常

调试过程

  1. 最初采用循环调用getLocation的方式,问题持续存在
  2. 切换为在前台服务任务中使用watchPosition,代码如下:
useEffect(() => { 
  ReactNativeForegroundService.add_task(() => { 
    backgroundWatchId.current = Geolocation.watchPosition( 
      async ({ coords }) => { 
        console.log('[ping]'); 
        if (currentRegattaRef.current?.checkpointsDetails.every((e) => e.completedTime)) { 
          currentRegattaRef.current = { ...currentRegattaRef.current, status: 'ready-to-upload' }; 
        } 
        if (!currentCheckpointRef.current || !currentRegattaRef.current || currentRegattaRef.current.status === 'ready-to-upload') return; 
        console.log(currentRegattaRef.current); 
        const { latitude, longitude } = coords; 
        const hasReached = verifyAreBoatIsWithinCheckpoint( 
          { lat: latitude, lng: longitude, }, 
          currentCheckpointRef.current.waypoint, 
        ); 
        ReactNativeForegroundService.update({ 
          id: 420, 
          title: 'Sailing is active! ⛵️', 
          message: `To checkpoints: ${getDistance( 
            { latitude, longitude }, 
            currentCheckpointRef.current.waypoint, 
            DISTANCE_ACCURACY, 
          )}`, 
          icon: 'ic_small_icon', 
          progress: { 
            max: currentRegattaRef.current.checkpointsDetails.length, 
            curr: currentCheckpointRef.current.index, 
          }, 
        }); 
        if (hasReached && isActiveRegattaRef.current) { 
          onArriveToTheCheckpointBackground(currentRegattaRef.current, currentCheckpointRef.current); 
        } 
      }, 
      (error) => { console.log(error); }, 
      GEO_OPTIONS, 
    ); 
  }, { 
    delay: 1000, 
    onLoop: false, 
    taskId: 'taskid', 
    onError: (e) => console.log('Error logging:', e), 
  }); 
}, []);

切换后后台仅正常运行约1分钟后再次失效

最终解决方案

针对Android 12的定位失效问题,需同时满足两个条件:

  • 必须使用Geolocation.watchPosition接口,禁止循环调用getLocation
  • 在应用系统设置中关闭电池优化,避免系统因省电策略强制终止定位任务

内容的提问来源于stack exchange,提问作者mRadek55

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:43:15