react-native - 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"
]
}
}
解决方案
经过一周的斗争,我终于找到了解决方案。事实证明,我收到此错误的原因仅仅是因为我在 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",
},
});
}
};
我希望这对那里的人有所帮助,请随时与我联系以获取有关此问题的进一步帮助。
推荐阅读
- php - PHP 7.0 - urlencode/urldecode 不是对称的
- php - laravel 查询生成器中的错误
- android - 如何将活动缩小到其内容的大小
- node.js - Dialogflow fullfilment代码在nodejs中使用twilio发送otp
- javascript - 如何摆脱HDMI?
- python - 如何在excel中写入不超过100万条来自python数据框的记录
- react-native - ReactNative/ReactJS 的浮动工具栏组件?
- javascript - 在选择时设置默认值
- node.js - Promise 的 Mocha 单元测试抛出错误
- docker - 如何以与环境无关的方式从 Docker 提供静态文件?