cordova背景模式插件中的问题

时间:2016-05-04 11:28:49

标签: cordova-plugins

我正在使用cordova后台模式插件在后台执行服务。它工作正常,直到应用程序最小化,但一旦应用程序从任务栏中删除或完全关闭,服务停止不应发生。 即使应用程序已关闭,该服务也应该运行。

帮助将不胜感激。 在此先感谢!!!!

1 个答案:

答案 0 :(得分:0)

这是我正在使用的以下代码

     cordova.plugins.backgroundMode.enable();
        cordova.plugins.backgroundMode.setDefaults({
            title:  'Osprey',
            ticker: '',
            text:   'App is running in background!!!'
        });
        cordova.plugins.backgroundMode.onactivate = function() {
          cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
              if (enabled) {
                var marker;

                var db = $cordovaSQLite.openDB("my.db"); //mobile
                //var db = window.openDatabase("my.db", '1', 'auto', 1024 * 1024 * 100);
                //$cordovaSQLite.execute(db,"DROP TABLE IF EXISTS Location;"); //drop a table
                $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Location (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude DOUBLE, longitude DOUBLE, date NUMERIC)");
                var options = {timeout: 20000, enableHighAccuracy: false};

                $cordovaGeolocation.getCurrentPosition(options).then(function(position){
                  var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                  lat = position.coords.latitude;
                  long = position.coords.longitude;
                  var mapOptions = {
                    center: latLng,
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                  };

                  $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
                  $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true').
                    then(function(data){ 
                      console.log(data);
                      $scope.address='Your current location is : ' +data.data.results[0].formatted_address;
                  });
                  google.maps.event.addListenerOnce($scope.map, 'idle', function(){

                  marker = new google.maps.Marker({
                      map: $scope.map,
                      animation: google.maps.Animation.DROP,
                      position: latLng,
                      draggable: true
                  }); 

                 var watchOptions = {maximumAge: 10000, timeout: 3000, enableHighAccuracy: false};
                 //var watchOptions = {frequency : 1000,timeout : 3000,enableHighAccuracy: false };
                 var watch = $cordovaGeolocation.watchPosition(watchOptions);

                 watch.then(
                    null,

                    function(err) {
                       console.log(err.message);
                    },

                    function(position) {
                       //start fetch tracking status
                      var data = {};
                      data.companyId = $window.localStorage['companyId'];
                      data.apiKey = $window.localStorage['apiKey'];
                      $http({
                         method: 'POST',
                         url: "http://192.241.86.4/api/fetch-tracking-status",
                         crossDomain:true,
                         data: data
                          }).success(function (response) {
                            var j = response.length - 1;
                            if (response[0].startTime === null || response[j].endTime === null) {
                              $cordovaToast
                                .show('No Tracking For Now!!!', 'long', 'center')
                                .then(function(success) {
                                  console.log('success');
                                }, function (error) {
                                  console.log('error');
                                });
                            } else {
                               console.log('tracking');
                               var latitude  = position.coords.latitude;
                               var longitude = position.coords.longitude;
                               var new_marker_position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                               marker.setPosition(new_marker_position);
                               var query = "INSERT INTO Location (latitude, longitude, date) VALUES (?,?,Date('now'))";
                                $cordovaSQLite.execute(db, query, [position.coords.latitude, position.coords.longitude]).then(function(res) {
                                    console.log("INSERT ID -> " + res.insertId);
                                }, function (err) {
                                    console.log(err.message);
                                });
                            }
                        },function error(response) {
                          console.log("Error Saving Data");
                      });
                    }
                 );
                 //watch.clearWatch();

                  var infoWindow = new google.maps.InfoWindow({
                      content: $scope.address
                  });

                  google.maps.event.addListener(marker, 'click', function () {
                      infoWindow.open($scope.map, marker);
                  });

                });

                if (navigator.connection.type == Connection.NONE){
                  $ionicPopup.confirm({
                    title: "Internet Disconnected",
                    content: "The internet is disconnected on your device. Please Connect Internet"
                  })
                } else {
                  var location = {};
                  location.locations = [];
                  setInterval(function(){
                    var query = "select * from Location";
                    location.apiKey = $window.localStorage['apiKey'];
                    $cordovaSQLite.execute(db, query)
                    .then(
                        function(result) {
                            if (result.rows.length > 0) {
                              for (var i=0; i < result.rows.length; i++) {
                                var object = {};
                                object.deviceId = $window.localStorage['imei'];
                                object.deviceName = $cordovaDevice.getModel();
                                object.phone = $window.localStorage['phone'];
                                object.companyId = $window.localStorage['companyId'];
                                object.createdDate = new Date().toUTCString();
                                object.batteryPercentage = $scope.showPercentage;
                                object.latitude = result.rows.item(i).latitude;
                                object.longitude = result.rows.item(i).longitude;
                                object.manual = "0";
                                location.locations.push(object);
                              }

                              $http({
                                 method: 'POST',
                                 url: "http://192.241.86.4/api/save-logs",
                                 crossDomain:true,
                                 data: location
                                  }).success(function (response) {
                                    $cordovaToast
                                      .show('Successfully Saved Location', 'long', 'center')
                                      .then(function(success) {
                                        console.log('success');
                                        var deleteQuery = "DELETE FROM Location";
                                        $cordovaSQLite.execute(db, deleteQuery).then(function(res) {
                                            console.log('deleted');
                                        }, function (err) {
                                            console.log(err.message);
                                        });
                                      }, function (error) {
                                        console.log('error');
                                      });
                                },function error(response) {
                                  console.log("Error Saving Data");
                                });
                            } else {
                              console.log('No places tracked');
                            }
                        },
                        function(error) {
                            console.log(error.message);
                        }
                      );
                  },20000);
                }

                }, function(error){
                  console.log("Could not get location");
                });
              } else {
                alert("Location is disabled");
                window.location.reload();
              }
          }, function(error) {
              console.log("The following error occurred: " + error);
          });
        }