Search code examples
ionic-frameworkcordova-plugins

cordova background geolocation plugin on reboot


I am building an ionic app with background geolocation plugin https://github.com/mauron85/cordova-plugin-background-geolocation.

I want to make an app to send its location after reboot. The plugin I am using seems to have the option, but it is not working properly. An app only sends its location to the server only after execute an app at least once after every boot.

Any help or suggestion would be appreciated. Thank you in advance!

My code is below

Configuration

backgroundGeolocation.configure(callbackFn, failureFn, {
            locationProvider: backgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
            desiredAccuracy: 10,
            stationaryRadius: 10,
            distanceFilter: 10,
            interval: 60000,
            maxLocations: 50,
            startOnBoot: true, // from my understanding, this should make an app track its location even after reboot
            stopOnTerminate: false
});

Callback Function

var callbackFn = function(location) {
        console.log('[js] BackgroundGeolocation callback:  ' + location.latitude + ',' + location.longitude);

        // Do your HTTP request here to POST location to your server.
        var link = API_URL;

        $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

        $http({
            method: 'POST',
            url: link,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj)
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            params: {
                'device': 'android',
            },
            data: {
                lat:location.latitude,
                lng:location.longitude,
            }
        }).success(function(data){
            console.log(data);
        }).error(function(data){
            console.log(data);
        });

        backgroundGeolocation.finish();
    };

Solution

  • i hope you would have found your answer by now, posting this might help others too.

    don't expect your callback to be executed after the reboot, as the activity might be killed, instead use url option of the plugin to continue sending your location updates to the server.