0

I am trying to get the location of device in a regular inteval of 10 or 20 seconds even in the the background. The background service is not working in android. I have followed the link

https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/blob/master/2.9.0/README.md

I am using cordova 2.9.0. My code is for background service is

var myService = cordova.require('cordova/plugin/myService');   
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {      
    getStatus();       
}
function handleSuccess(data) {
    updateView(data);
}

function handleError(data) {
    updateView(data);
}


function getStatus() 
{
    startService();
    myService.getStatus(function(r){handleSuccess(r)},
                        function(e){handleError(e)});
};

function startService() 
{
    myService.startService( function(r){handleSuccess(r)},
                                    function(e){handleError(e)});
}

function updateView(data) 
{
    var myVar;
    if (data.ServiceRunning) 
    {
        var options = { enableHighAccuracy: true };   
        myVar = setInterval(function()
        {
            console.log("running");                    
            navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
        }, 10000);
    }
    else
    {
        clearInterval(myVar);
    }
}

function stopService() {
    myService.stopService(function(r){handleSuccess(r)},
                          function(e){handleError(e)});
}

In the onSuccess method i have saved the location in a file. Now it is working fine with the app opening but not working in the background.

swati srivastav
  • 635
  • 4
  • 15

1 Answers1

1

I think the problem is that you call geolocation from javascript code (in the function updateView()). The moment you put the application in the background, executing of javascript code will stop (and so will calling of updateView() function). The only thing working when the application is in background is the service you launched.

So what you probably want to do is alter native android code of MyService class and call the geolocation inside service's doWork() function (something similar to what they did here, but instead of log you will do geolocation: https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/blob/master/2.9.0/MyService.java):

public class MyService extends BackgroundService {
    ...
    @Override
    protected JSONObject doWork() {
        //geolocate and store the results to FTP using native java code
        return result;
    }   
    ...

If you don't know how to do geolocation in android native code, this post might be useful for you: Good way of getting the user's location in Android

Community
  • 1
  • 1
Matej P.
  • 5,303
  • 1
  • 28
  • 44