mauron85 / cordova-plugin-background-geolocation

Background and foreground geolocation plugin for Cordova.
Apache License 2.0
538 stars 406 forks source link

When app is killed then background geolocation doen't call web service for tracking #426

Closed aaronharper123 closed 5 years ago

aaronharper123 commented 6 years ago

In below code i call web service at every 30 seconds , this code is fine when app is in running mode or background but when app is not running i.e. killed then no any web service is called. I want to call web service when app is killed also.

Your Environment

import { Injectable, NgZone } from '@angular/core'; import {ToastController} from 'ionic-angular'; import 'rxjs/add/operator/filter'; import { BackgroundGeolocation,BackgroundGeolocationConfig,BackgroundGeolocationResponse } from '@ionic-native/background-geolocation'; import { Geolocation, Geoposition } from '@ionic-native/geolocation'; import { ServerPushProvider } from '../server-push/server-push'; import { HttpService } from '../../pages/services/httpService'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { BatteryStatus } from '@ionic-native/battery-status'; import { BackgroundMode } from '@ionic-native/background-mode'; import { LocalNotifications } from '@ionic-native/local-notifications'; import { DbHandlerProvider } from '../db-handler/db-handler'; import moment from 'moment'; import { Diagnostic } from '@ionic-native/diagnostic'; declare let cordova: any;

@Injectable() export class LocationTracker {

  public watch: any;
  public lat: any;
  public lng: any;
  public cuuDate: any;
  public batteryLevel: number;
  public arrLocations: any = [];
  arrTime: any = [];
  locationInterval: number;
  UserId: any;

constructor(public zone: NgZone, public backgroundGeolocation: BackgroundGeolocation, private geolocation: Geolocation, public toastCtrl: ToastController, public serverPush: ServerPushProvider, public httpService: HttpService, public batteryStatus: BatteryStatus,private backgroundMode: BackgroundMode, private localNotifications: LocalNotifications, private diagnostic: Diagnostic, private dbHandlerProvider: DbHandlerProvider) { console.log('Hello LocationTrackerProvider Provider');

}

startTracking() {

  let now: any = new Date();
  now = moment(now).format();

  if(localStorage.getItem('UserId') == null){
      this.backgroundGeolocation.stop();
  } else {
      this.UserId = localStorage.getItem('UserId');
  }

  /////  For get location when device is in background
  this.cuuDate = new Date();
  this.cuuDate = moment(this.cuuDate).format();
  const subscription = this.batteryStatus.onChange().subscribe(status => {
       console.log(status.level, status.isPlugged);
       this.batteryLevel = status.level;
    });
  this.getForegroundLocation();
  this.startBackgroundLocation();

}

getForegroundLocation() { this.geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 10000 }).then(loc => { if(this.httpService.isOnline()){ this.arrLocations = this.dbHandlerProvider.get_location(); console.log('Location Data first: '+JSON.stringify(this.arrLocations)); setTimeout(()=> { if(this.arrLocations.length == 0){ // alert('1: '+this.arrLocations.length); this.serverPush.pushPosition({ UserId: this.UserId, LocationData: [ { Lat: loc.coords.latitude, Long: loc.coords.longitude, Date: this.cuuDate, BatteryPerc: this.batteryLevel } ] }); } else { this.serverPush.pushPosition({ UserId: this.UserId, LocationData: this.arrLocations }); setTimeout(() => { // delete database records this.dbHandlerProvider.delete_location(); },3000); } },1000); } else { this.dbHandlerProvider.add_location(loc.coords.latitude,loc.coords.longitude,this.cuuDate,this.batteryLevel); } }); }

startBackgroundLocation() {

  if(localStorage.getItem('UserId') == null){
      this.backgroundGeolocation.stop();
  } else {
      this.UserId = localStorage.getItem('UserId');
  }

   let config = {
     desiredAccuracy: 0,
     stationaryRadius: 0,
     distanceFilter: 0,
     notificationTitle: 'Background tracking',
     notificationText: 'ENABLED',
     foregroundService: true,
     debug: false,
     interval: 30000,
     url: 'http://property.zoomi.in:86/api/User/UserTracking',
     httpHeaders: {
      "Content-Type": "application/json"
    },
    postTemplate: {
        "UserId": this.UserId,    //  <-- Android ONLY:  HTTP POST params sent to your server when persisting locations.
        "LocationData": [
        {
          "Lat": this.lat,
          "Long": this.lng,
          "Date": this.cuuDate,
          "BatteryPerc": this.batteryLevel
        }
        ]
    },
     method: 'POST',
     autoSync: true,
     stopOnTerminate: false
   };

   this.backgroundGeolocation.configure(config).subscribe((location) => {

       let toast = this.toastCtrl.create({ message: 'Latlng updated successfully', duration: 1000, position: 'bottom'});
       toast.present();

       console.log('Lat: '+location.latitude + ' :: '+location.longitude );

       let aa = {
           title: 'Background Tracking',
           text: location.latitude + ' :: '+ location.longitude
       }
       cordova.plugins.notification.local.schedule(aa);

       this.lat = location.latitude
       this.lng = location.longitude

       this.cuuDate = new Date();
       this.cuuDate = moment(this.cuuDate).format();
       const subscription = this.batteryStatus.onChange().subscribe(status => {
            console.log(status.level, status.isPlugged);
            this.batteryLevel = status.level;
         });

         if( this.httpService.isOnline() ) {
             this.arrLocations = this.dbHandlerProvider.get_location();
             console.log('Location Data: '+JSON.stringify(this.arrLocations));
             setTimeout(()=> {
                 if(this.arrLocations.length == 0) {
                     // alert('3: '+this.arrLocations.length);
                     this.serverPush.pushPosition({
                         UserId: this.UserId,
                         LocationData: [
                            {
                              Lat: location.latitude,
                              Long: location.longitude,
                              Date: this.cuuDate,
                              BatteryPerc: this.batteryLevel
                            }
                          ]
                     });
                 } else {
                     console.log('4: '+this.arrLocations.length);
                     this.serverPush.pushPosition({
                         UserId: this.UserId,
                         LocationData: this.arrLocations
                     });
                     setTimeout(() => {
                         // delete databse records
                         this.dbHandlerProvider.delete_location();
                   },3000);
                 }
             },1000);
         } else {
             this.dbHandlerProvider.add_location(this.lat,this.lng,this.cuuDate,22);
         }

        this.backgroundGeolocation.finish();

   }, (err) => {
     console.log(err);
   });

   this.backgroundGeolocation.start();

}

stopTracking() {

  console.log('stopTracking');

  this.backgroundGeolocation.stop();

}

}

mauron85 commented 6 years ago

you've put a great effort into writing a lot in the issue, but please update it with the issue-template I provide.

aaronharper123 commented 6 years ago

i will update you with proper code, but please tell me first, if this plugin is also work when app is killed?

aaronharper123 commented 6 years ago

import { Injectable, NgZone } from '@angular/core'; import {ToastController} from 'ionic-angular'; import 'rxjs/add/operator/filter'; import { BackgroundGeolocation,BackgroundGeolocationConfig,BackgroundGeolocationResponse } from '@ionic-native/background-geolocation'; import { Geolocation, Geoposition } from '@ionic-native/geolocation'; import { ServerPushProvider } from '../server-push/server-push'; import { HttpService } from '../../pages/services/httpService'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { BatteryStatus } from '@ionic-native/battery-status'; import { BackgroundMode } from '@ionic-native/background-mode'; import { LocalNotifications } from '@ionic-native/local-notifications'; import { DbHandlerProvider } from '../db-handler/db-handler'; import moment from 'moment'; import { Diagnostic } from '@ionic-native/diagnostic'; declare let cordova: any; @Injectable() export class LocationTracker {

  public lat: any;
  public lng: any;
  public cuuDate: any;
  public arrLocations: any = [];
  UserId: any = '4';

constructor(public zone: NgZone, public backgroundGeolocation: BackgroundGeolocation, private geolocation: Geolocation, public serverPush: ServerPushProvider, public httpService: HttpService, public batteryStatus: BatteryStatus, private dbHandlerProvider: DbHandlerProvider) { console.log('Hello LocationTrackerProvider Provider'); this.cuuDate = new Date(); this.startTracking();

}

startTracking() { this.getForegroundLocation(); this.startBackgroundLocation(); }

getForegroundLocation() { this.geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 10000 }).then(loc => { if(this.httpService.isOnline()){ this.serverPush.pushPosition({ UserId: this.UserId, LocationData: [ { Lat: loc.coords.latitude, Long: loc.coords.longitude, Date: this.cuuDate, BatteryPerc: 44 } ] });

       } else {
           //   store in database
       }
   });

}

startBackgroundLocation() {

     let config = {
     desiredAccuracy: 0,
     stationaryRadius: 0,
     distanceFilter: 0,
     notificationTitle: 'Background tracking',
     notificationText: 'ENABLED',
     foregroundService: true,
     debug: false,
     interval: 5000,
     url: 'http://property.zoomi.in:86/api/User/UserTracking',
     httpHeaders: {
      "Content-Type": "application/json"
    },
    postTemplate: {
        "UserId": this.UserId,    //  <-- Android ONLY:  HTTP POST params sent to your server when persisting locations.
        "LocationData": [
        {
          "Lat": this.lat,
          "Long": this.lng,
          "Date": this.cuuDate,
          "BatteryPerc": 44
        }
        ]
    },
     method: 'POST',
     autoSync: true,
     stopOnTerminate: false
 };

   this.backgroundGeolocation.configure(config).subscribe((location) => {

           console.log('Lat: '+location.latitude + ' :: '+location.longitude );

           this.lat = location.latitude;
           this.lng = location.longitude;

           if( this.httpService.isOnline() ) {
               // this.arrLocations = this.dbHandlerProvider.get_location();

                       // alert('3: '+this.arrLocations.length);
                       this.serverPush.pushPosition({
                       UserId: this.UserId,
                       LocationData: [
                           {
                               Lat: location.latitude,
                               Long: location.longitude,
                               Date: this.cuuDate,
                               BatteryPerc: 44
                           }
                       ]
                   })
       } else {
           // store in databse
       }
       this.backgroundGeolocation.finish();

   }, (err) => {
     console.log(err);
   });

   this.backgroundGeolocation.start();

}

stopTracking() {

  console.log('stopTracking');

  this.backgroundGeolocation.stop();

}

}

aaronharper123 commented 6 years ago

please see above code, my problem is that i can not get location when app is killed. (i.e. this plugin is not work when app is not running for me)

devahernandez commented 6 years ago

I have the same problem, the application stops working when it is completely closed. It works well in the background and close-up.

blgsyrmhnds commented 6 years ago

are there any solution for that?Whep I close app tracking geolacation stop It does not work background for android and IOS

sakthibro commented 6 years ago

use background mode plugin

aaronharper123 commented 6 years ago

@sakthibro The app is worked fine in the background and in the foreground but not work after the app is killed.

OFMaurice commented 5 years ago

I have the same problem on android and ios. Foreground an background working fine but when the app is killed no more locations are posted to the url.

On Android i figured out that it is connected to the firebase plugin (cordova-plugin-firebase).

The destructor of the firebase plugin is called before the destructor of this plugin. And inside the firebase plugin destructor a 'System.exit(0);' is called and then the destructor of this plugin will not be called. When i uncomment -> '// System.exit(0);' it works fine.

Currently i am trying to firgure out whats the problem on ios..

@aaronharper123 do you have the firebase plugin installed also?

mauron85 commented 5 years ago

The destructor of the firebase plugin is called before the destructor of this plugin. And inside the firebase plugin destructor a 'System.exit(0);' is called and then the destructor of this plugin will not be called.

Nice observation. Can you please report this as an issue to cordova-plugin-firebase?

OFMaurice commented 5 years ago

I have taken a look to the current master of cordova-plugin-firebase and there it's already fixed. So for me it seems to be fixed by updating the firebase plugin.

papattes commented 5 years ago

Hello !

In android, i don't have this problem. however, with ios this not work when app is killed. Any solutions ?

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 5 years ago

This issue has been automatically closed, because it has not had recent activity. If you believe this issue shouldn't be closed, please reopen or write down a comment requesting issue reopening with explanation why you think it's important. Thank you for your contributions.