I’m creating an Ionic 4 app which should track users location while running - therefore it needs to work in the background.
I’ve implemented BackgroundGeolocation, following this tutorial: https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/
and the official docs: https://ionicframework.com/docs/native/background-geolocation/
The code is compiling but when deployed and run on an Android device I get this error:
But I already installed the plugin - If I run the command it suggests, I get: “plugin already installed”.
If I run on chrome://inspect I can see it never enters the backgroundGeolocation configure method, since it enters the err block.
What could be the cause?
Imports:
ionic cordova plugin add cordova-plugin-mauron85-background-geolocation@alpha
npm install --save @ionic-native/background-geolocation@5.0.0-beta.21
Here is my code:
app.module.ts (remaining import statements omitted):
import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
@NgModule({
declarations: [AppComponent, ViewInfoComponent],
entryComponents: [ViewInfoComponent],
imports: [BrowserModule, HttpClientModule, HttpModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
NavProviderService,
SygicPlacesService,
CurrentPositionService,
BackgroundGeolocation,
Geolocation,
Geofence,
TextToSpeech,
InAppBrowser,
BackgroundMode,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
in .ts file:
import { BackgroundGeolocation, BackgroundGeolocationConfig } from '@ionic-native/background-geolocation/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
constructor(public backgroundGeolocation: BackgroundGeolocation,
private geolocation: Geolocation) {}
startTracking() {
// Background tracking
const config: BackgroundGeolocationConfig = {
desiredAccuracy: 0,
stationaryRadius: 10,
distanceFilter: 10,
debug: true,
interval: 2000,
stopOnTerminate: true
};
this.backgroundGeolocation.configure(config).subscribe((location) => {
console.log('BackgroundGeolocation: ' + location.latitude + ', ' + location.longitude);
setTimeout(() => {
this.trackedRoute.push({lat: location.latitude, lng: location.longitude});
this.redrawPath(this.trackedRoute);
}, 0);
}, (err) => {
console.log(err);
});
this.backgroundGeolocation.start();
// Foreground tracking
this.positionSubscription = this.geolocation.watchPosition({
enableHighAccuracy: true
})
.pipe(
filter((p) => p.coords != undefined)
)
.subscribe(position => {
console.log(position);
setTimeout(() => {
this.trackedRoute.push({lat: position.coords.latitude, lng: position.coords.longitude});
this.redrawPath(this.trackedRoute);
}, 0);
});
}
stopTracking() {
this.backgroundGeolocation.stop();
this.positionSubscription.unsubscribe();
console.log('tracking stopped');
}