首页 > 解决方案 > Expo Location Error: Unhandled Promise Rejection: 错误: 无权使用后台定位服务

问题描述

即使应用程序在后台,我也想获取用户的位置。我以下列方式使用 expo-location 和 expo-task-manager:

import * as React from "react";
import {
  StyleSheet,
  StatusBar,
  Platform,
  SafeAreaView,
  TouchableOpacity,
  Text,
} from "react-native";
import * as TaskManager from "expo-task-manager";
import * as Location from "expo-location";

const STATUSBAR_HEIGHT = Platform.OS === "os" ? 20 : StatusBar.currentHeight;
const LOCATION_TASK_NAME = "background-location-task";

export default function TestingGround({ navigation }) {
  const onPress = async () => {
    const { status } = await Location.requestPermissionsAsync();
    if (status === "granted") {
      await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
        accuracy: Location.Accuracy.Highest,
      });
    }
  };
  return (
    <SafeAreaView style={styles.container}>
      <TouchableOpacity
        style={{
          height: 50,
          width: 300,
          backgroundColor: "red",
          justifyContent: "center",
          alignItems: "center",
        }}
        onPress={onPress}
      >
        <Text>Enable background location</Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
    paddingTop: STATUSBAR_HEIGHT,
    justifyContent: "center",
    alignItems: "center",
  },
});

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    // Error occurred - check `error.message` for more details.
    console.log("error", error);
    return;
  }
  if (data) {
    const { locations } = data;
    // do something with the locations captured in the background
    console.log("locations", locations);
  }
});

按下时,我收到错误:未处理的承诺拒绝:错误:未授权使用后台位置服务。定位服务已启用。我不明白我需要做什么。

我还在我的 App.json 中添加了以下内容,但没有成功:

 "android": {
     ...
      "permissions": [
        "CAMERA",
        "ACCESS_FINE_LOCATION",
        "ACCESS_BACKGROUND_LOCATION"]
    },
    "ios": {
      "supportsTablet": true,
      "infoPlist": {
        "UIBackgroundModes": [
          "location",
          "fetch"
        ]
      }
    }

标签: react-nativelocationexpo

解决方案


经过一周的斗争,我终于找到了解决方案。事实证明,我收到此错误的原因仅仅是因为我在 Expo 上运行此代码,它不允许后台位置获取。代码没有问题,我所要做的就是构建一个独立的应用程序(expo build:android),该应用程序的独立版本工作得很好,可以获取后台位置

我还向我的 Location.startLocationUpdatesAsync 传递了一个额外的参数,它提高了后台位置获取的效率,实际上让我可以看到应用程序正在通过如下通知获取后台位置:

const onPress = async () => {
  const { status } = await Location.requestPermissionsAsync();
  if (status === "granted") {
    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      accuracy: Location.Accuracy.BestForNavigation,
      timeInterval: 3000,
      foregroundService: {
        notificationTitle: "BackgroundLocation Is On",
        notificationBody: "We are tracking your location",
        notificationColor: "#ffce52",
      },
    });
  }
};

我希望这对那里的人有所帮助,请随时与我联系以获取有关此问题的进一步帮助。


推荐阅读