Skip to content

Instantly share code, notes, and snippets.

@rafwell
Created June 22, 2018 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafwell/c8eb0b3b877f76091cf61cab2f36641f to your computer and use it in GitHub Desktop.
Save rafwell/c8eb0b3b877f76091cf61cab2f36641f to your computer and use it in GitHub Desktop.
Bugged mauron85/cordova-plugin-background-geolocation 3.x with Ionic
import { Injectable } from '@angular/core';
import { ApiProvider } from '../../providers/api/api';
import { BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse } from '@ionic-native/background-geolocation';
import { NativeStorage } from '@ionic-native/native-storage';
import { UserProvider } from '../user/user';
import { Device } from '@ionic-native/device';
import moment from 'moment';
/*
Generated class for the LocationProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class LocationProvider {
constructor(
public apiProvider: ApiProvider,
public backgroundGeolocation: BackgroundGeolocation,
public nativeStorage: NativeStorage,
public userProvider: UserProvider,
public device: Device
) {
}
startLocationTracker() {
const config: BackgroundGeolocationConfig = {
notificationTitle: 'AP - Interno',
notificationText: 'Em execução',/*
notificationIconLarge: 'assets/icon/notification.png',
notificationIconSmall: 'assets/icon/notification-small.png',
*/desiredAccuracy: 10,
stationaryRadius: 50,
distanceFilter: 50,
debug: false, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false, // enable this to clear background location settings when the app terminates
startOnBoot: true,
locationProvider: 0, /** ANDROID_DISTANCE_FILTER_PROVIDER: 0, ANDROID_ACTIVITY_PROVIDER: 1 */
interval: 10000,
fastestInterval: 5000,
activitiesInterval: 10000,
};
this.backgroundGeolocation.configure(config)
.subscribe((location: BackgroundGeolocationResponse) => {
console.log('localização obtida', location);
this.saveLocationLocally(location);
// IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished,
// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
//this.backgroundGeolocation.finish(); // FOR IOS ONLY
});
// start recording location
this.backgroundGeolocation.start();
}
saveLocationLocally(location: BackgroundGeolocationResponse){
this.nativeStorage.getItem('locations')
.then(
locations => {
console.log('Localizações obtidas do nativeStorage', locations);
let pushLocation = {
'location': location,
'datetime': moment().format('YYYY-MM-DD HH:mm:ss'),
'user': {},
'startOnBoot': true,
'device': {
model: this.device.model,
uuid: this.device.uuid
}
};
this.userProvider.getCurrentUser().then(user=>{
pushLocation.user = user;
locations.push(pushLocation);
this.nativeStorage.setItem('locations', locations);
this.persistLocations(locations);
}).catch(err=>{
//Usuário não logado. Salvar a localização sem a informação do user
this.nativeStorage.setItem('locations', locations);
});
},
error => {
if (error.code === 2){
//primeira inserção
this.nativeStorage.setItem('locations', []).then(success=>{
this.saveLocationLocally(location);
}).catch(err=>console.log(err));
}
}
);
}
persistLocations(locations:any){
this.apiProvider.post('/api/locations', { 'locations': locations}).then(response=>{
//alert('Localizações enviadas para o servidor. ' + moment().format('YYYY-MM-DD HH:mm:ss'));
this.nativeStorage.remove('locations');
}).catch(error=>console.log(error));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment