背景地理位置ionic 3未配置

时间:2018-07-09 14:49:10

标签: angular typescript ionic3 cordova-plugins

当调用configure函数时,ionic 3上的背景地理位置崩溃。 我的应用程序取决于位置,背景信息将为我们提供有关用户的更多信息。这样,我的主页就会调用正常的地理位置插件并正常工作。我首先实现了背景地理定位,通常在home.ts的构造函数上调用了可注射的位置跟踪器。但是因为它甚至连通用的地理定位插件都崩溃了,所以我在初始化后开始调用它。

home.ts

    import { Diagnostic } from '@ionic-native/diagnostic';
    import { AppConfig } from './../../util/app-config';
    //import { Facebook } from '@ionic-native/facebook';
    import { MapPage } from './../map/map';
    import { MarkerModalPage } from './../marker-modal/marker-modal';
    import { LoginPage } from './../login/login';
    import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
    import { NavController, NavParams, ModalController, Content, Platform } from 'ionic-angular';
    import { CategoriesPage } from "../categories/categories";
    import { CategoryPage } from "../category/category";
    import { ItemPage } from "../item/item";
    import { SearchPage } from "../search/search";
    //import { CartPage } from "../cart/cart";
    import { MyAccountPage } from "../my-account/my-account";
    import { AdicionarPage } from "../adicionar/adicionar";
    import { GenericService } from "../../services/generic-service";
    import { GlobalThings } from "../../app/global-things";
    import { Storage } from '@ionic/storage';
    import { Geolocation } from '@ionic-native/geolocation';
    import { Usuario } from './../../domain/usuario';
    import { DomSanitizer } from '@angular/platform-browser';
    import L from "leaflet";
    import { SearchLocationPage } from '../search-location/search-location';
    import {DeeplinkData} from 'branch-cordova-sdk';
    import {  NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder';
    import {LoadingController} from 'ionic-angular';
    import {LocationTrackerProvider} from "../../providers/location-tracker/location-tracker";
    import {ServerPushProvider} from "../../providers/server-push/server-push";
    import {
        BackgroundGeolocation, BackgroundGeolocationConfig,
        BackgroundGeolocationResponse
      } from '@ionic-native/background-geolocation';

    ...

    public locationTracker: any;

    ...

    constructor(public nav: NavController,
            public loading: LoadingController,
            private generic: GenericService,
            private usuarioService: GenericService,
            private likeService: GenericService,
            private favoritoService: GenericService,

            public navParams: NavParams,
            public platform: Platform,
            public _DomSanitizer: DomSanitizer,
            public modalController: ModalController,
            private diagnostic: Diagnostic,
            public global: GlobalThings,
            private storage: Storage,
            private geolocation: Geolocation,
            private nativeGeocoder: NativeGeocoder,
            private serverPush: ServerPushProvider,
            private backgroundGeoloc: BackgroundGeolocation,)

    ...

    if (this.platform.is('cordova')) { //this basically checks permissions, calls normal geolocation then backgroundgeolocation and starts. It was done after the injectable implementation also failed as an attempt to make it work

                this.verificaPermissaoLocalizacao(result => {
                    if (result) {

                        //console.log(result);

                        this.verificaLocalizacaoAtiva(resAtiva => {
                            if (resAtiva) {
                                //console.log(resAtiva);
                                this.getLatLong(); //my normal geolocation function for the app which works 
                                this.locationTracker = new LocationTrackerProvider(this.serverPush,this.geolocation,this.backgroundGeoloc,this.usuarioService,this.diagnostic,this.platform);
                                this.locationTracker.start();
                            } else {
                                this.exibirAlertaLocalizacaoInativa = true;
                            }
                        });

                    } else {
                        this.solicitaPermissaoLocalizacao();
                    }
                });

            } else {
                this.getLatLong();
                this.locationTracker = new LocationTrackerProvider(this.serverPush,this.geolocation,this.backgroundGeoloc,this.usuarioService,this.diagnostic,this.platform);
                this.locationTracker.start();
            }
...

location-tracker.ts

import {Injectable} from '@angular/core';
import { Usuario } from '../../domain/usuario';
import { Diagnostic } from '@ionic-native/diagnostic';
import {Geolocation} from '@ionic-native/geolocation';
import { GenericService } from "../../services/generic-service";
import { Platform } from 'ionic-angular';
import { BackgroundMode } from '@ionic-native/background-mode';
import {
  BackgroundGeolocation, BackgroundGeolocationConfig,
  BackgroundGeolocationResponse
} from '@ionic-native/background-geolocation';
import {catchError} from 'rxjs/operators';
import {EmptyObservable} from "rxjs/observable/EmptyObservable";
import {ServerPushProvider} from "../server-push/server-push";

@Injectable()
export class LocationTrackerProvider {
  usuario = new Usuario();

  constructor(private serverPush: ServerPushProvider,
              private geolocation: Geolocation,
              private backgroundGeolocation: BackgroundGeolocation,
              private usuarioService: GenericService,
              private diagnostic: Diagnostic,public platform: Platform,private backgroundMode: BackgroundMode, private plt: Platform) {
                //this.initBackgroundMode();
                platform.ready().then(() => {
                  backgroundMode.setDefaults({ silent: true });
                  backgroundMode.enable();
                        //backgroundMode.disableWebViewOptimizations();
                        console.log("Init tracking");
                        this.startTracking();
                        // Custom code for updating the location 
                        // or do similar functionality
                        // use timeout or interval accordingly to execute the functionality in loop
                });
  }


  startTracking(){
    this.startBackgroundLocation();
  }

//--------------------------------------------------------------------------------

  stopTracking(){
    this.backgroundGeolocation.stop();
  }

  startBackgroundLocation(){
    const backgroundOptions: BackgroundGeolocationConfig = {
      desiredAccuracy: 10,
      stationaryRadius: 20,
      distanceFilter: 30,
      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(backgroundOptions)
      .subscribe((location: BackgroundGeolocationResponse) => {
        console.log("location: "+ JSON.stringify(location));
        let pos = {
          "latitude": location.latitude,
          "longitude": location.longitude,
        };
        if (location) {
          console.log("will now push");
          this.serverPush.pushPosition(pos);
        }
        this.backgroundGeolocation.finish();
      }),error =>{
        console.log("Response fail: "+error);
      };
    this.backgroundGeolocation.start();



  }

}

server-push.ts(此功能正常运行,已通过常规地理位置功能进行了测试)

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import { GenericService } from './../../services/generic-service';
import { Usuario } from '../../domain/usuario';
import { Device } from '@ionic-native/device';
import { Storage } from '@ionic/storage';
import { GlobalThings } from './../../app/global-things';
import {LocaisUsuarioVO } from "../position";

@Injectable()
export class ServerPushProvider {
  submitAttempt: boolean = false;
  usuario = new Usuario();

  constructor(private readonly httpClient: HttpClient,private genericService: GenericService,private device: Device,private storage: Storage,
    private global: GlobalThings) {
  }

  pushPosition(pos){
  this.submitAttempt = true;

      this.genericService.setEntity("privado/usuario", true);

      this.usuario.uuiDispositivo = this.device.uuid;
      this.genericService.PostarLocalizacao(pos).subscribe(
        resp => {
            console.log(resp);
        },
        error => {
          this.global.erro(error);
        });

  }

 /* pushPosition(pos: Position): void {
    this.httpClient.post(`${this.serverURL}`, pos)
      .subscribe(() => {
      }, error => this.pushError(error));
  }*/


}

0 个答案:

没有答案