Доступ к запущенному фоновому процессу в PhoneGap с помощью AngularJS и Ionic

У меня проблема с фоновым процессом геолокации (https://github.com/christocracy/cordova-plugin-background-geolocation) в проекте phonegap с angularjs и ionic. Процесс идет нормально, но иногда я не могу его остановить.
Если приложение запущено на переднем плане, все работает нормально. Но когда я запускаю фоновую службу, а затем нажимаю кнопку «Домой» на своем устройстве (Samsung Galaxy S2), процесс выполняется в фоновом режиме -> правильно. И вот я снова открываю приложение и пытаюсь остановить фоновый процесс, но в этот раз не получается.

Кажется, у меня неправильный экземпляр процесса.

Это мой код:

var bgGeo;

angular.module('starter.services', [])
.factory('LocationService', function($http, $location){
    function startBackgroundLocation() {
        var gpsOptions = {
            enableHighAccuracy : true,
            timeout: 10000,
            maximumAge: 5000
        };
        navigator.geolocation.getCurrentPosition(function(location) {
            console.log('Location from Phonegap');
        },
        function (error){
            alert('error with GPS: error.code: ' + error.code + ' Message: ' + error.message);
        },gpsOptions);


        bgGeo = window.plugins.backgroundGeoLocation;

        /**
        * This would be your own callback for Ajax-requests after POSTing background geolocation to your server.
        */
        var yourAjaxCallback = function(response) {
            ////
            // IMPORTANT:  You must execute the #finish method here to inform the native plugin that you're finished,
            //  and the background-task may be completed.  You must do this regardless if your HTTP request is successful or not.
            // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
            //
            //
            bgGeo.finish();
        };

        /**
        * This callback will be executed every time a geolocation is recorded in the background.
        */
        var callbackFn = function(location) {
            alert('[js] BackgroundGeoLocation callback:  ' + location.latitudue + ',' + location.longitude);
            // Do your HTTP request here to POST location to your server.
            //
            //

            // This is never called in Android
            yourAjaxCallback.call(this);
        };

        var failureFn = function(error) {
            alert('BackgroundGeoLocation error');
        }

        // BackgroundGeoLocation is highly configurable.
        bgGeo.configure(callbackFn, failureFn, {
            url: apiUrl + '/position/', // <-- only required for Android; ios allows javascript callbacks for your http
            params: {                                               // HTTP POST params sent to your server when persisting locations.
               auth_token: localStorage.getItem('gcmToken')
            },
            desiredAccuracy: 10,
            stationaryRadius: 20,
            distanceFilter: 30,
            debug: true // <-- enable this hear sounds for background-geolocation life-cycle.
        });

        // Turn ON the background-geolocation system.  The user will be tracked whenever they suspend the app.
        // wenn der Service bereits läuft, nicht mehr starten
        bgGeo.start();
    }

    function stopBackgroundLocation(){
        bgGeo.stop();
    }

    return {
        start: function(){
            init();
        },
        stop : function () {
            stopBackgroundLocation();
        }
    }
}

Когда я звоню LocationService.stop() после возобновления работы приложения, фоновая геолокация не останавливается.

Кто-нибудь знает, что не так или что мне нужно добавить? Спасибо.

@Aleks: Может быть, ты знаешь решение?


person sbr11    schedule 06.07.2014    source источник
comment
Теперь ни у кого нет решения или хотя бы идеи или подсказки? Пожалуйста, это действительно важно, потому что это для моего экзамена. Благодарю вас!   -  person sbr11    schedule 09.07.2014


Ответы (1)


Я использую сейчас эту функцию:

function stopService(){
  var bgGeoService = window.plugins.backgroundGeoLocation
  bgGeoService.stop()
}

И это, кажется, работает. Но есть и другой подход, см. эту ссылку: https://github.com/christocracy/cordova-plugin-background-geolocation/issues/48

Надеюсь это поможет.

person sbr11    schedule 12.08.2014