#angular #cordova #ionic-framework #cordova-plugins #ionic-native
#angular #кордова #ionic-framework #cordova-плагины #ionic-родной
Вопрос:
Я не могу понять, почему этот плагин не работает в моем приложении:https://ionicframework.com/docs/native/background-geolocation
Мой код:https://plnkr.co/edit/LAfbfU5edGhQmmkg?open=lib/app.tsamp;deferRun=1
Он запускает startBackgroundGeolocation(), но никогда не вводит «.subscribe», он даже не входит в блок «.then()» в app.component.ts в строке 54:
import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { AngularFireDatabase } from '@angular/fire/database';
import * as firebase from 'firebase';
import * as moment from 'moment-timezone';
import { Platform } from '@ionic/angular';
import {
BackgroundGeolocation,
BackgroundGeolocationConfig,
BackgroundGeolocationResponse,
BackgroundGeolocationEvents
} from '@ionic-native/background-geolocation/ngx';
import { AuthService } from './auth/auth.service';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
positionSubscription: Subscription;
constructor(
private platform: Platform,
private dbRt: AngularFireDatabase,
private backgroundGeolocation: BackgroundGeolocation
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.startBackgroundGeolocation();
});
}
startBackgroundGeolocation() {
const config: BackgroundGeolocationConfig = {
desiredAccuracy: 10,
stationaryRadius: 1,
distanceFilter: 0,
interval: 1000,
fastestInterval: 1000,
activitiesInterval: 1000,
stopOnStillActivity: false,
startForeground: true,
startOnBoot: true,
debug: true, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false // enable this to clear background location settings when the app terminates
};
this.backgroundGeolocation.configure(config).then(() => {
this.backgroundGeolocation
.on(BackgroundGeolocationEvents.location)
.subscribe((location: BackgroundGeolocationResponse) => {
console.log(location);
if (location.speed === undefined) {
location.speed = 0;
}
this.dbRt.database
.ref(`/gps/${this.authService.userprofile.value.uid}`)
.push({
date: moment.tz('Indian/Mauritius').format('DD-MM-YYYY HH:mm:ss'),
timestamp: firebase.database.ServerValue.TIMESTAMP,
platform: 'background GPS !!!'
})
.then((res) => {
// this.backgroundGeolocation.finish(); // FOR IOS ONLY
})
.catch((error) => {
// this.backgroundGeolocation.finish(); // FOR IOS ONLY
});
// 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 operations are successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
});
});
// start recording location
this.backgroundGeolocation.start().then((state) => {
console.log('state: ' state);
});
}
}
Похоже, что он даже не запускает backgroundGeolocation в строке 84:
this.backgroundGeolocation.start().then((state) => {
console.log('state: ' state);
});
Я использую appflow для создания apk и протестировал его на Samsung S8 / Android 7.0, он даже не запрашивает у меня предоставления какого-либо доступа, как это было для обычной геолокации. Я ожидал бы получить разрешение backgroundGeolocation для разрешения, но ничего не появляется.
Когда я пытаюсь реализовать обычный плагин геолокации (https://ionicframework.com/docs/native/geolocation ), все работает нормально, я получаю разрешение на предоставление геолокации при первом запуске приложения, и я могу сохранить широту / lng в своей базе данных.
Ответ №1:
Вы установили
Желаемая точность: 10
и чтобы это работало, вам нужно иметь новое местоположение на расстоянии 10 м от старого.