2

I am working on a Cordova application which needs to send current location of user to server after every 10 seconds. For that, I am using Geolocation plugin. Here are my code snippets:

$rootScope.startListeningForLocation = function() {
            $rootScope.locationListenerId = setInterval(function() {

              navigator.geolocation.getCurrentPosition(
                  $rootScope.onSuccessForLocation,
                  $rootScope.onErrorForLocation_High,
                  {maximumAge:600000, timeout:7000, enableHighAccuracy: true}
                  );
            }, 5000);

        };

$rootScope.onSuccessForLocation = function(position) {
            var lat = position.coords.latitude, lng=position.coords.longitude;
            gLat = lat;
            gLng = lng; 
}

function startLocationRefreshLoop() {
    if(locationReloadInterval) clearInterval(locationReloadInterval);
    var locationReloadInterval = setInterval(function() {
       $('#btn-location').trigger('click');
    }, LOCATION_UPDATE_INTERVAL);   
}
...

<div id='btn-location' ng-show="false" ng-click='updateLocationToServer()'></div>
...
    $rootScope.updateLocationToServer = function() {
        if(!isConnected()) {
            dbService.logLocation();
        } else {
            var prom = Api.post(apiURL+'/employee/'+$rootScope.user.id+'/current_location', {location:{latitude: gLat, longitude: gLng}});
            prom.then(function(data) {
                console.log('updateLocation::> ' + JSON.stringify(data) + 'gLat:' + gLat + ', gLng' + gLng);
            });
        }

    };

Everything works very fine when app is in foreground i.e. the app gets the location stored in gLat and gLng variables and send it to server every 10 seconds. But when goes to background and phone is in sleep mode, it is showing some strange behaviour. Strange in the sense that instead of calling updateLocationToServer() every 10 seconds, it gets called after every minute and sometimes it gets more worse. I don't know how 10 seconds are being interpreted as one minute in sleep mode. I want to know what are the possible reasons for such a delay? My application is mainly for taxi drivers and want to keep track of them all the time. The client's whole business depends on this thing and its like make it or break it thing. Your suggestions please.

Edit: And my client is using 3G and 4G network to test the app.

Khawar Raza
  • 15,870
  • 24
  • 70
  • 127
  • for this to work properly you need a plugin that has got a android-service that can be run in background. like one of [mine](https://github.com/blauharley/Cordova-Reminder/blob/master/src/android/ReminderService.java) It is not exacly what you need but the principle is the same a service might send location to your server. Here is a famous [one](https://github.com/christocracy/cordova-plugin-background-geolocation) that uses a service as well. – Blauharley Apr 24 '15 at 19:24

0 Answers0