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权限,但无法触发检查点,通知显示的地理位置无变化 - 仅当其他应用使用定位功能时,本应用定位才恢复正常
调试过程
- 最初采用循环调用
getLocation的方式,问题持续存在 - 切换为在前台服务任务中使用
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
相关产品推荐
相关产品推荐

