首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何保持更新位置,即使对象没有使用世博后台服务Location.startLocationUpdatesAsync()移动,

如何保持更新位置,即使对象没有使用世博后台服务Location.startLocationUpdatesAsync()移动,
EN

Stack Overflow用户
提问于 2020-04-11 06:44:06
回答 1查看 1.6K关注 0票数 0

请提供以下内容: 1. SDK版本: 37 2.平台( Android /iOS/web/all):Android

我正在使用Expo版本: 37,在平台Android中,我想问,有没有办法让应用程序通知当前用户的位置--即使用户不移动,我尝试每5分钟在中记录用户位置,它与Location.startLocationUpdatesAsync一起工作(见下面的代码),但是如果用户坐着的时候没有移动很长时间,它就没有更新位置,是如何记录用户位置的,尽管用户没有移动,因为下面的代码会每10秒启动一次,但是如果对象没有移动,它不生成新的位置数据(请参见const {纬度,经度}= data.locations.coords)

代码语言:javascript
运行
复制
  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);
    }
  });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-11 07:41:02

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

  1. 不是使用Location.startLocationUpdatesAsync侦听位置更改,而是设置一个间隔,每5分钟检索一次当前位置,例如:

代码语言:javascript
运行
复制
setInterval(() => {
  const location = await getCurrentLocation();
  doSomethingWithLocation(location);
}, 300000)

  1. 继续像您一样监听位置更改,但也设置一个间隔,每5分钟从您的location服务中检索当前位置,并使用该间隔。如果在此期间没有更改位置,则只需发送前一个值.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61153035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档