How to detect when app is minimized? Handling real time messaging

I have two parts to the question.

I’m testing an app that is somewhat real time messaging which hits the database every few seconds to check for new messages.

When i minimized the app, it’s continuing to hit the database. I’m not sure how this can scale properly with multiple users.

  1. Is this common with apps? How do other apps handle this.
  2. Is there anyway I can detect when an app is minimized and potentially reduce the calls.

I would recommend pause and resume handlers. See the Platform docs.

1 Like

Hmm I’m running ionic react. In the platform docs for the react section they don’t show pause or resume events being in the docs:

@omarel0 Did you resolve this, I’ll looking for the same functionality and can’t find it in the docs?


I did figure it out eventually. I’m using react and ionic though. I’ll look through my code and post it for you.

1 Like

Me too. That would be very helpful, thanks.

This is what I ended up coming up with. It was tested and works for Ionic with React. It’s a capacitor plugin:

This will trigger when the app is active. I think if you use the else statement it will trigger when the app is minimized, but I don’t recall testing that part. Someone can test and report back.

//import the plugin at the top
import { Plugins, AppState} from '@capacitor/core';

     const { App } = Plugins;
     App.addListener('appStateChange', (state: AppState) => {
       if (state.isActive == true) {
           // Do this when app is active
       }  else {
          // Do this when app is inactive

Additional Sources: (all the capacitor plugins)

Thanks @omarel0, I haven’t had the opportunity to try this yet but just wanted to say thanks for posting, much appreciated.

Thanks, this was just the hint I needed!

It looks a little different in Capacitor 3:

  import { App } from '@capacitor/app';

  App.addListener('appStateChange', ({ isActive }) => {
    // console.log('App state changed. Is active?', isActive);
    if (isActive) {
      // Do fun stuff.

Capacitor 3 docs on App

1 Like