Ionic 2 How to use Cordova events pause resume
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);
nyluje
Updated on June 19, 2022Comments
-
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 thewindow
like it is explained here.Or is there anyother known way to access
document.addEventListener(...)
when in Ionic 2? -
nyluje over 7 yearsI won't try it right now but this seems correct and documented so I validate the answer.
-
SR1 over 6 yearsWhat can I do while it is paused? As in what is the point of pause and resume?
-
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 over 3 yearsDoes nothing in the browsers though, so fairly useless.