【发布时间】:2021-09-14 08:03:24
【问题描述】:
我正在做一些事情,如果应用程序处于后台并且设备处于睡眠状态,我需要跟踪后台位置。我目前让它在后台为应用程序工作,但是当设备处于睡眠状态时它会停止跟踪。我正在为应用程序使用 Expo,并在 Expo Location 旁边使用 Expo Task Manager 在后台获取位置。 任何人都知道如何在应用程序处于后台且设备处于睡眠模式时获取位置?
这是代码
import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
const App = () => {
useEffect(() => {
(async () => await _askForLocationPermission())();
});
this.backgroundLocationFetch = async () => {
const { status } = await Location.requestBackgroundPermissionsAsync();
if (status === 'granted') {
console.log('cmon dance with me!')
await Location.startLocationUpdatesAsync('FetchLocationInBackground', {
accuracy: Location.Accuracy.Balanced,
timeInterval: 3000,
distanceInterval: 1,
foregroundService: {
notificationTitle: 'Live Tracker',
notificationBody: 'Live Tracker is on.'
}
});
}
}
const _askForLocationPermission = async () => {
(async () => {
let { status } = await Location.requestBackgroundPermissionsAsync();
if (status !== 'granted') {
setgpsErrorMsg('Permission to access location was denied');
}
})();
};
return(
<View>
<Text></Text>
</View>
)
};
TaskManager.defineTask('FetchLocationInBackground', ({ data, error }) => {
if (error) {
console.log("Error bg", error)
return;
}
if (data) {
const { locations } = data;
console.log("BGGGG->", locations[0].coords.latitude, locations[0].coords.longitude);
}
});
export default App;
【问题讨论】:
-
你能添加你的代码吗?
-
@FrancescoClementi 我添加了代码
-
您使用的是什么 SDK 版本的 expo?我认为在 40 岁以上这对于请求权限将不再有效?
标签: android react-native geolocation location expo