Ionic 2 How to use Cordova events pause resume

17,564

Solution 1

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();
  }
}

Solution 2

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);
Share:
17,564
nyluje
Author by

nyluje

Updated on June 19, 2022

Comments

  • nyluje
    nyluje almost 2 years

    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?

  • nyluje
    nyluje over 7 years
    I won't try it right now but this seems correct and documented so I validate the answer.
  • SR1
    SR1 over 6 years
    What can I do while it is paused? As in what is the point of pause and resume?
  • Andrew
    Andrew almost 5 years
    @SR1 you can change a route, or if your app has a PIN to unlock it, you cand use it on resume (like some banking apps do, etc)
  • Oliver Dixon
    Oliver Dixon over 3 years
    Does nothing in the browsers though, so fairly useless.