Пауза и возобновление событий - Cordova & Angular8 - PullRequest
0 голосов
/ 10 октября 2019

В настоящее время я пытаюсь использовать события pause и resume для приложения Cordova + Angular 8.

constructor() {
    document.addEventListener("pause", this.buttonPressed, false);
    document.addEventListener("resume", this.powerTestSuccess, false);
}

buttonPressed(){
    this.pressed = true;
    console.log('PAUSE EVENT RUNNING');
}

powerTestSuccess(){
   setTimeout(function() {
       console.log("RESUME EVENT RUNNING");
       console.log(this.pressed);
       if(this.pressed == true){
           this.doSomething();
       } else {
           this.doSomethingElse();
       }
   }, 0);
}

Я вижу, как работают console.logs, однако this.pressed не манипулируют, а также функции doSomething() & doSomethingElse() не запускаются. Я прочитал в документации к кордове, что When called from a resume event handler, interactive functions such as alert() need to be wrapped in a setTimeout() call with a timeout value of zero, or else the app hangs.

Это причина, по которой ничего кроме console.log не работает?

Что я могу сделать, чтобы это работало?

1 Ответ

0 голосов
/ 12 октября 2019

:: glups ::, вам нужно использовать ngZone. Представьте, что у вас есть сервис, подобный

export enum CordovaEvent {BackButton,Resume,Pause}
@Injectable()

export class CordovaEventService {

    private listeningSource:Subject<CordovaEvent>=new Subject<CordovaEvent>();
    cordovaEvent:Observable<CordovaEvent>=this.listeningSource.asObservable();
    isCordoba:boolean=false;
    constructor() {
    }

    sendEvent(evento:CordovaEvent)
    {
        this.listeningSource.next(evento);
    }
}

// В вашем app.main

  ngAfterViewInit() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
  }
  onDeviceReady() {
    // Control pause, resume and backbutton
    document.addEventListener('pause', this.onPause.bind(this), false);
    document.addEventListener('resume', this.onResume.bind(this), false);
    document.addEventListener("backbutton", this.onBackKeyDown.bind(this), false);
    this.cordovaEventService.isCordoba=true;

  };

  onPause() {
    this.cordovaEventService.sendEvent(CordovaEvent.Pause);
  };

  onResume() {
    this.cordovaEventService.sendEvent(CordovaEvent.Resume);
  };

  onBackKeyDown(e) {
    this.cordovaEventService.sendEvent(CordovaEvent.BackButton);
    e.preventDefault();
    e.stopPropagation();

  };

В компоненте вы можетеподписаться на «cordovaEvent» Я использую «классическую» takeWhile () для отмены подписки, переменную alive:boolean=true и в ngOnDestroy this.alive=false

this.cordovaEventService.cordovaEvent.pipe(takeWhile(() => this.alive))
  .subscribe((event: CordovaEvent) => {
  if (event == CordovaEvent.BackButton) {
    //An event that no need has reflecj in Angular not need run in ngZone
    if (this.pagina=="Home") {
      navigator.notification.confirm("Do you really quit out?", 
            this.onConfirm, "App-example", ["OK", "Cancel"]);
    }
    else
    {
      this.ngZone.run(()=>{
        !--make some thing--
      })
    }
  }
});

Ну, эта работа, потому что я проверил, но представьте, что -не проверять - мы улучшаем сервис, работающий в ngZone, собственный сервис, меняем функции onPause, onResumen и onBackButton

  onPause() {
      this.ngZone.run(()=>{
         this.cordovaEventService.sendEvent(CordovaEvent.Pause);
      })
  };

  onResume() {
    this.ngZone.run(()=>{
       this.cordovaEventService.sendEvent(CordovaEvent.Resume);
    })
  };

  onBackKeyDown(e) {
    this.ngZone.run(()=>{
        this.cordovaEventService.sendEvent(CordovaEvent.BackButton);
      })
    e.preventDefault();
    e.stopPropagation();

  };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...