后台服务可以在前台完美运行,但是当应用程序在后台运行时,将停止发送更新的位置信息。
这主要是在应用程序投入生产时发生的,这里有更多详细信息:
这是任务:
TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
console.log("Entro a este task")
if (error) {
console.log(error)
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { locations } = data;
console.log(locations)
let getLastTime = await AsyncStorage.getItem('lastTime');
console.log(getLastTime)
if(getLastTime){
let timeInterval = moment(new Date()).diff(getLastTime,'seconds')
if(timeInterval<=10) {
return
}
console.log(timeInterval)
console.log("Este es el intervalo")
}
await LocationAPI.sendCurrentLocation(locations[0].coords).then(async res=>{
console.log(res)
console.log("Se envio")
await AsyncStorage.setItem('lastTime', new Date().toString())
}).catch(err=>{
alert(err.message)
})
// do something with the locations captured in the background
}
});
这是调用此任务的函数:
const { status } = await Location.requestPermissionsAsync();
if (status === "granted") {
await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
accuracy: Location.Accuracy.BestForNavigation,
showsBackgroundLocationIndicator: true,
activityType: Location.ActivityType.AutomotiveNavigation,
foregroundService: {
notificationTitle: "Tienes una orden activa",
notificationBody: "Entregando pedido...",
notificationColor: "#RRGGBB",
},
});
}