Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 481
Maik Kwi Avatar asked Nov 04 '25 16:11

Maik Kwi


1 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.

like image 123
Sébastien Avatar answered Nov 06 '25 05:11

Sébastien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!