Я использую этот плагин https://github.com/mauron85/cordova-plugin-background-geolocation для генерации фоновых событий.оно генерируется, когда устройство начинает двигаться, но когда я останавливаюсь на одном месте, скажем, на 1 минуту, а затем снова начинает двигаться, чем остановились фоновые события.не знаю почему.
Я использую интервал в одну минуту для отслеживания местоположения фона.но когда движение устройства останавливается на 1-2 минуты, фоновые события не генерируются.
***************** app.js **************************
BackgroundGeolocation.configure({
locationProvider: 0,
desiredAccuracy: 0,
stationaryRadius: 1,
distanceFilter: 1,
stopOnStillActivity: false,
stopOnTerminate: false,
startForeground: false,
startOnBoot: true,
maxLocations: 1000,
notificationTitle: 'Carrier Application',
notificationText: 'Tracking your location',
debug: true,
interval: 60000,
fastestInterval: 10000,
activitiesInterval: 10000,
postTemplate: {
lat: '@latitude',
lon: '@longitude'
}
});
document.addEventListener('deviceready',
updateCurrentPositionService.onDeviceReady, false);
$ionicPlatform.on('pause', function () {
// Handle event on pause/background
console.log('inside pause/background event');
updateCurrentPositionService.backgroundLocationStart();
updateCurrentPositionService.destroyInterval();
updateCurrentPositionService.backgroundLocationTracking();
});
$ionicPlatform.on('resume', function () {
// Handle event on resume/foreground
console.log('inside resume/foreground event');
updateCurrentPositionService.backgroundLocationEnd();
updateCurrentPositionService.destroyBackgroundInterval();
updateCurrentPositionService.updateLocation();
});
********************* updateCurrentPositionService.js **************************
function updateLocation() {
$timeout(function () {
deviceId = localStorage.getItem('deviceId');
}, 100);
vm.repeatThis = setInterval(function () {
BackgroundGeolocation.checkStatus(
function (status) {
if (status.locationServicesEnabled) {
var intransitLength = JSON.parse(localStorage.getItem("intransitLength"));
var initialUpdateCurrentPositionApiCall = JSON.parse(localStorage.getItem("initialUpdateCurrentPositionApiCall"));
if (intransitLength > 0 && initialUpdateCurrentPositionApiCall == 2) {
vm.isOnline = $cordovaNetwork.isOnline();
if (vm.isOnline) {
console.log('inside updatelocation foreground event');
BackgroundGeolocation.getCurrentLocation(
function (locations) {
callUpdateCurrentPosition({ deviceId: deviceId, latitude: Number(Math.round(locations.latitude + 'e4') + 'e-4'), longitude: Number(Math.round(locations.longitude + 'e4') + 'e-4') });
});
}
}
} else {
var locationAlert = $ionicPopup.alert({
title: 'Turn on location',
template: 'Please turn your location services on to track the shipments picked up by you.'
});
locationAlert.then(function (res) {
console.log(res);
})
}
}
);
}, 60000);
}
function backgroundLocationTracking() {
$timeout(function () {
deviceId = localStorage.getItem('deviceId');
}, 100);
vm.backgroundMode = setInterval(function () {
BackgroundGeolocation.checkStatus(
function (status) {
if (status.locationServicesEnabled) {
var intransitLength = JSON.parse(localStorage.getItem("intransitLength"));
var initialUpdateCurrentPositionApiCall = JSON.parse(localStorage.getItem("initialUpdateCurrentPositionApiCall"));
if (intransitLength > 0 && initialUpdateCurrentPositionApiCall == 2) {
vm.isOnline = $cordovaNetwork.isOnline();
if (vm.isOnline) {
console.log('inside backgroundLocationTracking background event');
BackgroundGeolocation.getCurrentLocation(
function (locations) {
callUpdateCurrentPosition({ deviceId: deviceId, latitude: Number(Math.round(locations.latitude + 'e4') + 'e-4'), longitude: Number(Math.round(locations.longitude + 'e4') + 'e-4') });
});
}
}
} else {
var locationAlert = $ionicPopup.alert({
title: 'Turn on location',
template: 'Please turn your location services on to track the shipments picked up by you.'
});
locationAlert.then(function (res) {
console.log(res);
})
}
}
);
}, 60000);
}
//destroyInterval() is used to clear set interval
function destroyInterval() {
clearInterval(vm.repeatThis);
}
function destroyBackgroundInterval() {
clearInterval(vm.backgroundMode);
}
//callUpdateCurrentPosition() is to perform the API call
function callUpdateCurrentPosition(obj) {
vm.baseSer.create({ id: '' }, {}, { "data": obj }, {}, false).then(function (data) {
if (data.success === true) {
console.log("LOCATION UPDATED", obj);
}
}, function (err) {
console.log("error in update location:", err);
});
};
// new code for background location started
function onDeviceReady() {
BackgroundGeolocation.on('location', function (location) {
// handle your locations here
// to perform long running operation on iOS
// you need to create background task
BackgroundGeolocation.startTask(function (taskKey) {
// execute long running task
// eg. ajax post location
// IMPORTANT: task has to be ended by endTask
BackgroundGeolocation.endTask(taskKey);
});
});
BackgroundGeolocation.on('stationary', function (stationaryLocation) {
// handle stationary locations here
});
BackgroundGeolocation.on('error', function (error) {
console.log('[ERROR] BackgroundGeolocation error:', error.code, error.message);
});
BackgroundGeolocation.on('start', function () {
console.log('[INFO] BackgroundGeolocation service has been started');
});
BackgroundGeolocation.on('stop', function () {
console.log('[INFO] BackgroundGeolocation service has been stopped');
});
BackgroundGeolocation.on('authorization', function (status) {
console.log('[INFO] BackgroundGeolocation authorization status: ' + status);
if (status !== BackgroundGeolocation.AUTHORIZED) {
// we need to set delay or otherwise alert may not be shown
setTimeout(function () {
var showSettings = confirm('App requires location tracking permission. Would you like to open app settings?');
if (showSetting) {
return BackgroundGeolocation.showAppSettings();
}
}, 1000);
}
});
BackgroundGeolocation.checkStatus(function (status) {
console.log('[INFO] BackgroundGeolocation service is running', status.isRunning);
console.log('[INFO] BackgroundGeolocation services enabled', status.locationServicesEnabled);
console.log('[INFO] BackgroundGeolocation auth status: ' + status.authorization);
// you don't need to check status before start (this is just the example)
if (!status.isRunning) {
BackgroundGeolocation.start(); //triggers start on start event
}
});
}
Я ожидаю, что фоновые события будут генерироваться, даже если приложениев одном месте.и снова, когда пользователь начинает движение, также должны генерироваться события.Заранее спасибо !!