我一直在开发一个react本机应用程序,在该应用程序中,我必须每隔10秒获取地理位置,并将其更新到服务器。当模拟器处于活动状态/处于前台时,我也能做到这一点。
然而,当应用程序被最小化时,它就不起作用了。我尝试使用expo任务管理器,但该函数在后台似乎无法运行。
这里的错误是什么?我已经附上了我的代码和输出。
我正在使用安卓11使用模拟器和个人设备。
这是我的代码:
import * as Permissions from 'expo-permissions';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
//Navigator
import Navigator from './routing/Routing';
const Main = () => {
const [gpsLatitude, setgpsLatitude] = useState(null);
const [gpsLongitude, setgpsLongitude] = useState(null);
const [batteryLevel, setBatteryLevel] = useState(null);
useEffect(() => {
(async () => await _askForLocationPermission())();
const interval = setInterval(() => {
uploadDataAtInterval();
}, 10000);
return () => clearInterval(interval);
});
const backgroundLocationFetch = async () => {
const { status } = await Location.requestPermissionsAsync();
if (status === 'granted') {
console.log('cmon dance with me!')
await Location.startLocationUpdatesAsync('FetchLocationInBackground', {
accuracy: Location.Accuracy.Balanced,
timeInterval: 10000,
distanceInterval: 1,
foregroundService: {
notificationTitle: 'Live Tracker',
notificationBody: 'Live Tracker is on.'
}
});
}
}
const _askForLocationPermission = async () => {
(async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setgpsErrorMsg('Permission to access location was denied');
}
})();
};
const uploadDataAtInterval = async () => {
console.log('upload using axios');
}
const getGPSPosition = async () => {
let location = await Location.getCurrentPositionAsync({accuracy:Location.Accuracy.High});
setgpsLatitude(location.coords.latitude);
setgpsLongitude(location.coords.longitude);
}
backgroundLocationFetch();
return(
<Navigator />
)
};
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 Main;
输出:
BGGGG 12.88375 80.08169
BGGGG 12.88375 80.08169
App: Not logged on now false //at every 10secs
App: Not logged on now false
App: Not logged on now false
App: Not logged on now false
App: Not logged on now false
App: Not logged on now false
对于稍后关注此问题的任何人,请确保在物理设备上测试您的应用程序。Emulator并不真正正确地支持任务管理器和后台获取!