React Native Android免费后台定位失效问题及解决方案
Android React Native免费后台定位解决方案
我在为Android平台的React Native应用寻找免费的后台定位方案,使用了一款react-native-geolocation库,但它不支持后台定位。
我编写的代码如下:
useEffect(() => { Geolocation.setRNConfiguration({ skipPermissionRequests: false, locationProvider: 'android', }) Geolocation.watchPosition( ({ coords: { latitude: lat, longitude: lon }}) => { // my code here... }, (error) => console.error(error), { interval: 1000, enableHighAccuracy: true, distanceFilter: 1 }, ) }, [])
这段代码在应用前台时运行正常,但切换到后台后就无法监听位置变化。我了解到一款react-native-background-geolocation模块,但它是付费的。尝试过多个替代库,要么已经过时,要么无法在后台正常工作。
我的React Native版本是0.71.6。
更新:已找到解决方案!
使用Expo的Location库解决了问题,纯React Native项目可按照官方指南安装Expo模块来使用。
经过测试的可用代码如下(用于监听地理位置变化并获取坐标):
import { useEffect } from 'react' import type { FC } from 'react' import * as Location from 'expo-location' import * as TaskManager from 'expo-task-manager' const App: FC = () => { // ... 原有代码 useEffect(() => { (async () => { let { status } = await Location.requestForegroundPermissionsAsync() if (status !== 'granted') { console.error('位置访问权限已被拒绝') return } TaskManager.defineTask('WATCH_BG_GEO', ({ data: { locations }, error }) => { if (error) return // // 地理位置变化后的处理逻辑写在这里 // // 示例 - 获取经纬度 const newCoords = { lat: locations[0].coords.latitude, lon: locations[0].coords.longitude, } // 后台模式下依然可以正常运行!! }) // 地理位置变化监听启动器 Location.startLocationUpdatesAsync('WATCH_BG_GEO', { accuracy: Location.Accuracy.BestForNavigation, showsBackgroundLocationIndicator: true, timeInterval: 1000, activityType: Location.ActivityType.AutomotiveNavigation, distanceInterval: 1, foregroundService: { notificationTitle: 'GPS', notificationBody: '已启用', } }) })() }, []) return ( // ... ) }
内容的提问来源于stack exchange,提问作者DukVanDuken
相关产品推荐
相关产品推荐

