首页 > 解决方案 > 如何使用博览会后台服务 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);
    }
  });

标签: react-nativeexpo

解决方案


由于您需要每 5 分钟记录一次用户位置,我可以看到两个选项:

  1. 不要使用 监听位置变化Location.startLocationUpdatesAsync,而是设置一个间隔,每 5 分钟检索一次当前位置,例如:
setInterval(() => {
  const location = await getCurrentLocation();
  doSomethingWithLocation(location);
}, 300000)
  1. 像你一样继续监听位置变化,但还要设置一个间隔,每隔 5 分钟从你的位置服务中检索当前位置并使用它。如果在那段时间内位置没有改变,它只会发送以前的值。

推荐阅读