Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2 How to use Cordova events pause resume

I am surprised to not find any thread already created on that topic.

In Ionic 2 there is the lifecycle of the pages in NavController: ionView[didLoad|didLeave|...]

And there are the Cordova events that are supposed to be called like this: document.addEventListener("pause", onPause, false);

I am in a situation where I want to get the Cordova events. Ionic lifecylce of pages is not a fit because what I want to do need to happen when the device gets in the onResume status whichever page shows on.

I haven't tried it yet, because I was hoping to find a good lead here before to keep on going, but I have the feeling that document won't be accessible from Angular2, Ionic2 and that I will probably will have to add a service to access the window like it is explained here.

Or is there anyother known way to access document.addEventListener(...) when in Ionic 2?

like image 228
nyluje Avatar asked Nov 05 '16 11:11

nyluje


2 Answers

I was also able to get document.addEventListener working from the constructor method of an Ionic2 page e.g.

  document.addEventListener("pause", function() {
    // do something
  }, true);

  document.addEventListener("resume", function() {
    // do something
  }, true);
like image 149
xke Avatar answered Nov 16 '22 04:11

xke


The way it works in Ionic 2 is detailed here

Basically, you need to inject the Platform instance in your page and subscribe to the pause event emitter:

import { Component } from '@angular/core';
import { Subscription } from 'rxjs';
import { Platform } from 'ionic-angular';

@Component({...})
export class AppPage {
  private onResumeSubscription: Subscription;

  constructor(platform: Platform) {
    this.onResumeSubscription = platform.resume.subscribe(() => {
       // do something meaningful when the app is put in the foreground
    }); 
  } 

  ngOnDestroy() {
    // always unsubscribe your subscriptions to prevent leaks
    this.onResumeSubscription.unsubscribe();
  }
}
like image 42
David M. Avatar answered Nov 16 '22 02:11

David M.