When the platform is ready, in app.component.ts, I am initiating a call to setInterval() to execute a function every second indefinitely. The executed function checks and starts the geolocation background service every 24 seconds. If the service is already running, it does nothing. After 6 seconds since the service was started, I stop the service and make an http post request to send location data to an API. The service is then started again after 24 seconds and the process is repeated again. It doesn’t stop.
What is the performance impact when doing it like this or making use of setInterval() like this?
Here’s sample code:
export class MyApp {
rootPage:any = HomePage;
// variable to keep the previous timestamp
old_time: number = null;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public trackingService: TrackingService, backgroundMode: BackgroundMode) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
// enable background mode for iOS.
backgroundMode.enable();
// start a custom background service defined in this component
this.startBackgroundService();
statusBar.styleDefault();
splashScreen.hide();
});
}
// a background service to start and stop user location tracking in intervals
startBackgroundService() {
// execute a function every second for location tracking
setInterval(() => {
let new_time = new Date().getTime();
// start the tracking service every 24 seconds
if((this.old_time === null) || ((new_time - this.old_time) > 24000)) {
this.old_time = new_time;
// the startService method starts the background geolocation services
// the startService method checks if the service is already running or not before starting it again
this.trackingService.startService();
}
// stop the tracking service after 6 seconds since it was started
if((new_time - this.old_time) > 6000) {
// http request takes place un the stopService method
// the stopService method also has an additional check to see if the service is already running or not
this.trackingService.stopService();
}
this.trackingService.est = Math.round(24 - ((new_time - this.old_time) / 1000));
}, 1000);
}
}
Code Repo: https://github.com/kobusbeets/ionic2-background-geolocation/