如何使用expo后台服务location.startLocationUpdatesAsync()保持更新位置,即使对象没



请提供以下信息:1.SDK版本:372.平台(安卓/iOS/web/all(:安卓

我使用的是Expo SDK版本:37,使用Android平台,我想问,有没有一种方法可以让应用程序通知当前用户位置,即使用户没有移动,我尝试每5分钟在中记录一次用户位置。它与location.startLocationUpdatesAsync一起工作(见下面的代码(,但如果用户长时间不移动,例如在用户坐着的时候,它没有更新位置,尽管用户没有移动,但我如何记录用户位置,因为startLocationUpdatesAsync下面的代码将每10秒启动一次,但如果对象没有移动,它不会生成新的位置数据(请参见const{纬度,经度}=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分钟记录一次用户位置,我可以看到两个选项:

  1. 不使用Location.startLocationUpdatesAsync侦听位置更改,而是设置一个每隔5分钟检索当前位置的间隔,例如:
setInterval(() => {
const location = await getCurrentLocation();
doSomethingWithLocation(location);
}, 300000)
  1. 继续监听位置更改,但也设置一个间隔,每隔5分钟从定位服务中检索当前位置并使用该间隔。如果在此期间位置没有更改,它将简单地发送以前的值

您可以执行以下操作(其中CHANGE_FETCH是当您想在位置发生变化时更新,NO_CHANGE_FETCH是当位置没有变化时更新(:

// starts the background location updates
const startLocationUpdates = async () => {
// start the task
console.log('gets here');
Location.startLocationUpdatesAsync(NO_CHANGE_FETCH, {
accuracy: Location.Accuracy.Highest,
distanceInterval: 0, // minimum change (in meters) betweens updates
deferredUpdatesInterval: MILI * STAG_MAXTIME, // minimum interval (in milliseconds) between updates
// foregroundService is how you get the task to be updated as often as would be if the app was open
foregroundService: {
notificationTitle: 'Using your location',
notificationBody: 'To turn off, go back to the app and switch something off.',
},
});
Location.startLocationUpdatesAsync(CHANGE_FETCH, {
accuracy: Location.Accuracy.Highest,
distanceInterval: MIN_DIST, // minimum change (in meters) betweens updates
deferredUpdatesInterval: MILI * MOVING_MAXTIME, // minimum interval (in milliseconds) between updates
// foregroundService is how you get the task to be updated as often as would be if the app was open
foregroundService: {
notificationTitle: 'Using your location',
notificationBody: 'To turn off, go back to the app and switch something off.',
},
});
};  

最新更新