Unable to provide geolocation when app in background mode

Hi Everyone,

I want to make ionic app to run in the background and get geolocation.

Basic installation as follows.

  1. nodejs 8.11.3 (npm v5.6.0)
  2. Cordova 8.0.0
  3. Ionic 3.20.0

Other plugins:

npm install --save @ionic-native/core@latest

ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation

ionic plugin add cordova-plugin-mauron85-background-geolocation
npm install --save @ionic-native/background-geolocation

ionic cordova plugin add cordova-plugin-statusbar
npm install --save @ionic-native/status-bar

ionic cordova plugin add cordova-plugin-inappbrowser
npm install --save @ionic-native/in-app-browser

Provider: LocationTracker

location-tracker.ts

import { Injectable, NgZone } from '@angular/core';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { Geolocation, Geoposition } from '@ionic-native/geolocation';
import 'rxjs/add/operator/filter';
 
@Injectable()
export class LocationTracker {
 
  public watch: any;   
 
  constructor(public zone: NgZone, 
    public backgroundGeolocation: BackgroundGeolocation, 
    public geolocation: Geolocation) {
 
  }

  startTracking() {
 
    // Background Tracking
   
    let config = {
      desiredAccuracy: 0,
      stationaryRadius: 20,
      distanceFilter: 10,
      debug: false,
      interval: 60000
    };
   
    this.backgroundGeolocation.configure(config).subscribe((location) => {
   
      //console.log('BackgroundGeolocation:  ' + location.latitude + ',' + location.longitude);
      // Run update inside of Angular's zone
      this.zone.run(() => {
        this.lat = location.latitude;
        this.lng = location.longitude;
      });
   
    }, (err) => {
   
      console.log(err);
   
    });
   
    // Turn ON the background-geolocation system.
    this.backgroundGeolocation.start();
   
   
    // Foreground Tracking
   
    let options = {
      frequency: 3000,
      enableHighAccuracy: true
    };

    this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
      console.log(position);  
       
      // Run update inside of Angular's zone
      this.zone.run(() => {
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
      });
    });
  }

  stopTracking() {
    console.log('stopTracking');
    this.backgroundGeolocation.finish();
    this.watch.unsubscribe();
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Geolocation } from '@ionic-native/geolocation';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HttpClientModule } from '@angular/common/http';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { LocationTracker } from '../providers/location-tracker/location-tracker';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(MyApp, { animate: false })
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Geolocation,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    LocationTracker,
    BackgroundGeolocation
  ]
})
export class AppModule {}

home.ts

import { Component} from '@angular/core';
import { NavController,Platform } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { HttpClient } from '@angular/common/http';
import { LocationTracker } from '../../providers/location-tracker/location-tracker';

@Component({
	selector: 'home-page',
  templateUrl: 'home.html'
})

export class HomePage {

  constructor(public navCtrl: NavController, 
    public geolocation: Geolocation, 
    public http: HttpClient, 
    public locationTracker: LocationTracker,
    public rest: Rest,
    public platform: Platform) {
      this.platform.ready().then(() => {
        this.locationTracker.startTracking();
      });
  }

}

Application is running fine on foreground mode, but it’s unable to generate geolocation in background mode.

Is there anything wrong in the code? How can I fix it?

Regards

P.S. I am running this app on Android device ( Nougat )

Unfortunately for your users, even if you did manage to achieve these three goals, you would also get #4: utterly demolish battery life. I would urge you to rethink this so that your app is not preventing the device from sleeping.

Thanks for the reply @rapropos.

Please provide me with a better approach to achieve the existing thing.

Regards.

At a minimum, I would pool all data collected during background operation and only do the network uploading when the app is in the foreground.

OK. That’s a good idea, but I am building a tracking app. So I have another app where I want to show the movement of this device in the google map. If the app goes background mode for 10 min, then the movement will also stop for 10 min.

This all sounds like one of the creepiest ideas I’ve ever heard.

From your reply I can understand that there are much better ideas. Some other concept which I am lacking due to my limited knowledge. May be I can achieve in some other way. Something like getting geolocation for device from google itself? Is it possible?

I am really sorry wasting your time. I should have researched more before come to here. I found Hypertrack is the thing which I wanted.

I appreciate the time you have given. Thanks @rapropos

Can anyone shed some light on the issue?

Thanks and regards.

Hello Jerry,

Do you find any solution ?

Thx

I installed

and add the code for wake_lock
https://github.com/katzer/cordova-plugin-background-mode/issues/400#issuecomment-484077499

Anyone tried @mauron85/cordova-plugin-background-geolocation?

hello jerry,
I am working on a same project, where i want to track user location every 10 minutes for a healthcare project.
Have you found out something which can help me out.

i have tried ionic background-geolocation but it stops in background after a few minutes.
Thanks and regards.

For anyone getting into this: At the Moment there is only one working, good and very well maintained Plugin to archive this: https://github.com/transistorsoft/cordova-background-geolocation-lt

This Plugin is free for Debug Mode and iOS but requires a Licence for Android, which costs. In our Team we decided to buy it and it works perfectly.

I realize that this is for obvious reasons going to be an area of huge interest, but may I just plead with everybody that is contemplating writing apps that track user location and upload it to take just a moment to consult with security and/or legal experts? There are a bunch of really serious concerns surrounding data privacy with apps like this, that may even expose you as app authors to legal liability.