如何使用博览会后台服务Location.startLocationUpdatesAsync(),

时间:2020-04-11 06:44:06

标签: react-native expo

请提供以下内容: 1. SDK版本:37 2.平台(Android / iOS /网络/全部):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);
    }
  });

1 个答案:

答案 0 :(得分:1)

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

  1. 代替使用Location.startLocationUpdatesAsync监听位置更改,而是设置一个间隔,该间隔将每5分钟检索一次当前位置,例如:
setInterval(() => {
  const location = await getCurrentLocation();
  doSomethingWithLocation(location);
}, 300000)
  1. 继续像您一样侦听位置更改,但还设置了一个间隔,该间隔将每隔5分钟从您的位置服务中检索当前位置并使用该间隔。如果在此期间位置未更改,则只会发送先前的值。
相关问题