react-native - React Native Expo:使用任务管理器在后台获取地理位置
问题描述
我一直在开发一个反应本机应用程序,我必须以 10 秒的间隔获取地理位置并将其更新到服务器。当模拟器处于活动状态/在前台时,我能够做同样的事情。
但是,当应用程序最小化时,它不起作用。我尝试使用 expo 任务管理器,但该功能在后台运行时似乎没有运行。
这里有什么错误?我附上了我的代码和输出。
我正在使用模拟器和个人设备使用 android 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
解决方案
对于稍后查看此内容的任何人,请确保您在物理设备上测试您的应用程序。模拟器并不真正支持任务管理器和后台获取正确!
推荐阅读
- android - 无法从我的 Android 应用程序下载来自 youtube 或 vimeo 的视频
- powerapps - 文本传入时字段增长
- ansible - Ansible wait_for 使用主机别名测试清单中主机的防火墙开口
- codeigniter - Google 身份验证未返回某些用户的用户名
- c++ - std::launch::async 不同线程的数量是否正确?
- javascript - 我如何在运行上一个调用时为 api 调用调用 saga?
- raid - 断电后如何在重新添加时重新组装 RAID5 阵列
- python - 如何手动将权重设置为 keras 中默认权重的输入特征?
- ios - 如何将解析数据存储到某个变量中
- c# - asp.net 样板 odata 计数