react-native - 如何使用博览会后台服务 Location.startLocationUpdatesAsync() 保持更新位置,即使对象不移动,
问题描述
请提供以下信息: 1. SDK 版本:37 2. 平台(Android/iOS/web/all):Android
我正在使用 Expo SDK 版本:37,使用平台 Android,我想问一下,有没有办法让应用程序通知当前用户位置,即使用户不动,我尝试每 5 分钟记录一次用户位置,它正在使用Location.startLocationUpdatesAsync (见下面的代码),但如果用户长时间不移动,例如当用户坐着时,它不会更新位置,虽然用户没有移动,但我如何记录用户位置,因为 startLocationUpdatesAsync 下面的代码将启动每个10 秒,但如果对象没有移动,它不会生成新的位置数据(参见 const { latitude, longitude } = data.locations[0].coords)
useEffect(() => {
async function startWatching() {
locationService.subscribe(onLocationUpdate)
try {
const { granted } = await Location.requestPermissionsAsync();
if (!granted) {
throw new Error('Location permission not granted');
}
let isRegistered = await TaskManager.isTaskRegisteredAsync('firstTask');
if (isRegistered) {
TaskManager.unregisterTaskAsync('firstTask')
}
await Location.startLocationUpdatesAsync('firstTask', {
accuracy: Location.Accuracy.BestForNavigation,
timeInterval: 10000,
activityType: Location.ActivityType.AutomotiveNavigation,
deferredUpdatesInterval: 15000
});
} catch (e) {
setErr(e);
}
};
startWatching()
}, []);
TaskManager.defineTask('firstTask', ({ data, error }) => {
if (error) {
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { latitude, longitude } = data.locations[0].coords
locationService.setLocation({latitude, longitude})
// console.log('locations', locations);
}
});
解决方案
由于您需要每 5 分钟记录一次用户位置,我可以看到两个选项:
- 不要使用 监听位置变化
Location.startLocationUpdatesAsync
,而是设置一个间隔,每 5 分钟检索一次当前位置,例如:
setInterval(() => {
const location = await getCurrentLocation();
doSomethingWithLocation(location);
}, 300000)
- 像你一样继续监听位置变化,但还要设置一个间隔,每隔 5 分钟从你的位置服务中检索当前位置并使用它。如果在那段时间内位置没有改变,它只会发送以前的值。
推荐阅读
- elasticsearch - 错误:无法找到或加载主类 org.elasticsearch.tools.java_version_checker.JavaVersionChecker
- c++ - 这些初始化有什么区别?
- azure-functions - Azure 函数在 .net 框架上具有持久函数
- python - 使用 Python 从 SharePoint 2013 连接/下载文件
- python - 在 SQL Server (2017) 上运行多个 python 版本
- html - 如何使用css正确定位选择元素和图标?
- regex - VSCode 正则表达式删除函数调用
- php - ajax调用期间禁止Yii2 403
- python - Re.sub 重叠 python
- javascript - 从 Binance API 获取数据到 Javascript 数组