Ionic event not triggered when app goes in background (plattform pause)

Viewed 2710

I want to perform some actions when my app goes to the background—e.g., when pressing the home button. (I am testing on an Android device.)

I tried the following in my app.component.ts:

this.platform.ready().then(() => {
    this.platform.pause.subscribe(async () => {
      alert("Pause event detected"); 
      //Do stuff here
    });

    this.platform.resume.subscribe(async () => {
      alert("Resume event detected");
      //Do stuff here
    });
…

I also tried:

App.getState().then((result) => {
  alert("state active?" + result.isActive);
});

No listener is triggered when the app goes to background (e.g., by pressing the home button). But when I start the app again, all events are triggered (in this case, the alerts), including the platform.pause event.

I am using Ionic 9 and Capacitor.

Am I misunderstanding something? What could be the problem?

2 Answers

You can use the event listeners provided in Capacitor's App API.

// Import the relevant stuff from Capacitor
import { Plugins, AppState } from '@capacitor/core';
const { App } = Plugins;

Then in your AppComponent class

this.platform.ready().then(() => {

    App.addListener('appStateChange', (state: AppState) => {
        if (state.isActive) {
            console.log('App has become active');
        } else {
            console.log('App has become inactive');
        }
    });

})

Note that you can test this in a desktop browser as well by switching to another tab.

Ok... things work. The problem was, that I had both variants in code active.

Related