你能用 React Native 跟踪背景地理定位吗?

Gra*_*ant 11 javascript android geolocation reactjs react-native

问题

即使应用程序不再处于前台(例如,用户已切换到另一个应用程序或切换到主屏幕并锁定了他们的手机),我也希望能够跟踪用户的位置。

用例是用户跟踪跑步。他们可以打开应用程序并在运行开始时按“开始”,然后切换或最小化应用程序(按主页按钮)并锁定屏幕。在跑步结束时,他们可以将应用程序带到前台并按“停止”,应用程序会告诉他们跑步的距离。

是否可以使用纯 React Native 在 iOS 和 Android 上跟踪后台地理定位?

关于地理定位的 react native 文档(https://facebook.github.io/react-native/docs/geolocation)不是很清楚或详细。上面的文档链接没有提到 iOS 上的背景地理定位(没有完全清楚),但没有提到 Android。

我最好使用 Expo 吗?

Eri*_*oor 13

2019 年世博会 33.0.0 更新:

Expo 首先在他们的 SDK 32.0.0 中弃用它以满足应用商店指南,但随后在 SDK 33.0.0 中重新打开它

从那时起,它们使实现后台定位变得非常容易。使用我用来使后台地理定位工作的这段代码片段。

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';

const LOCATION_TASK_NAME = 'background-location-task';

export default class Component extends React.Component {
  onPress = async () => {
    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      accuracy: Location.Accuracy.Balanced,
      timeInterval: 5000,
    });
  };

  render() {
    return (
      <TouchableOpacity onPress={this.onPress} style={{marginTop: 100}}>
        <Text>Enable background location</Text>
      </TouchableOpacity>
    );
  }
}

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    alert(error)
    // Error occurred - check `error.message` for more details.
    return;
  }
  if (data) {
    const { locations } = data; 
    alert(JSON.stringify(locations); //will show you the location object
    //lat is locations[0].coords.latitude & long is locations[0].coords.longitude
    // do something with the locations captured in the background, possibly post to your server with axios or fetch API 
  }
});
Run Code Online (Sandbox Code Playgroud)

代码就像一个魅力。需要注意的一件事是您不能在 Expo App 中使用地理定位。但是,您可以在独立构建中使用它。因此,如果您想使用后台地理定位,您必须使用此代码,然后expo build:ios上传到应用商店,以便能够获取用户的后台位置。

此外,请注意,您必须包括

"UIBackgroundModes":[
          "location",
          "fetch"
        ]
Run Code Online (Sandbox Code Playgroud)

info.plist您的app.json文件部分。

  • 世博会无法在 Android 上跟踪后台位置 (2认同)