52

Is there any way to check whether the app is running in foreground or background in ionic/cordova/phonegap, I need to use it on android and ios, thanks a lot

4
  • 2
    ... read the documentation. A pause eventlistener will tell you when the user closes the app. The resume eventlistener will do the opposite of that.
    – Sithys
    Apr 13, 2015 at 13:13
  • 1
    thanks Sithys, in that case, I need to store a variable(let's say A) in the local storage, whose value will be changed by resume/pause eventlistener, then according to the A's value to determine the app's foreground/background, right? but It's feels not directly, is there any more directly method? Thanks in advance Apr 13, 2015 at 15:10
  • The Resume and Pause events will be fired independently from a variable or sth like this. They will be fired if the user presses the home button, or if the user resumes the application.
    – Sithys
    Apr 13, 2015 at 15:34
  • 1
    @Sithys - simply listening for fired events doesn't answer the question that @user1521398 asked "Is there any way to check whether the app is running in foreground or background"... @user1521398 - yes you would need to use the pause and resume events with a variable to store the state (see the answered provided by @jurer). May 25, 2017 at 11:55

9 Answers 9

58

Use the two Events "Pause" and "Resume". You will find all Events here in the Apache Cordova Events Documentation.

Event - Pause:

  • The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application.

Event - Resume

  • The resume event fires when the native platform pulls the application out from the background.

You can add an Eventlistener for that into your code. For those two Events that would be:

Pause - Quick Example

document.addEventListener("pause", onPause, false);

function onPause() {
    // Handle the pause event
}

Or Full Example like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Pause Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        document.addEventListener("pause", onPause, false);
    }

    // Handle the pause event
    //
    function onPause() {
    }

    </script>
  </head>
  <body onload="onLoad()">
  </body>
</html>

Resume - Quick Example

document.addEventListener("resume", onResume, false);

function onResume() {
    // Handle the resume event
}

Or Full Example like this

<!DOCTYPE html>
<html>
  <head>
    <title>Resume Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        document.addEventListener("resume", onResume, false);
    }

    // Handle the resume event
    //
    function onResume() {
    }

    </script>
  </head>
  <body onload="onLoad()">
  </body>
</html>

Try that out and let me know, if you need further help!

3
  • 1
    Thanks the details example, Sithys Apr 13, 2015 at 23:08
  • hi, the pause/resume events do not fire immediately once the device is ready. My app was supposed to detect this event on another page in the app and during that time, my app could be at the background. How can I achieve this?
    – niCad
    Mar 17, 2017 at 4:50
  • I need to know if the app has been launched in background (like after a VoIP push). Do you know how we could do that?
    – Hugo H
    Mar 13, 2018 at 10:42
51

For Ionic 2 and Ionic 3 the solution is:

import { Platform } from 'ionic-angular';

@Component({
  template: `OK`
})

constructor(public platform: Platform) {

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

      if (platform.is('cordova')){

        //Subscribe on pause i.e. background
        this.platform.pause.subscribe(() => {
          //Hello pause
        });

        //Subscribe on resume i.e. foreground 
        this.platform.resume.subscribe(() => {
          window['paused'] = 0;
        });
       }
    });
}

12
  • why you are setting window['paused'] = 0; ? after checking the app is in foreground? Nov 27, 2019 at 9:53
  • Yes when app came to foreground mode I set it for my case. You don't need it. Nov 28, 2019 at 10:06
  • okay, cool, actually in iOS when app is in foreground state I am not getting firebase push notification. so I am thinking about creating own local notification, by checking platform and foreground condition... and pass the data into it. Nov 28, 2019 at 11:36
  • What kid of plugin do you use for notifications? Nov 28, 2019 at 14:23
  • phonegap plugin push Nov 29, 2019 at 6:40
13

A small service for Ionic based on Sithys answer:

factory('BackgroundCheck', function($ionicPlatform){
    var service = {};
    var inBackground = false;

    $ionicPlatform.ready(function() {        
        document.addEventListener("resume", function(){inBackground = false;}, false);
        document.addEventListener("pause", function(){inBackground = true;}, false);
    });

    service.isActive = function(){
        return inBackground == false;
    }
    return service;    
})
8

"Is there any way to check whether the app is running in foreground or background?"

Yes.

1) When an app becomes inactive (runs in the background) Cordova fires the pause event, and when an app becomes active again (brought to the foreground) Cordova fires the resume event.

2) From these events, one can use a variable to store the state as "foreground" or "background".

document.addEventListener("deviceReady", function readyCallback() {


    var isAppInForeground = true;


    document.addEventListener("pause", function pauseCallback() {
      isAppInForeground = false;
    }, false);

    document.addEventListener("resume", function resumeCallback() {
      isAppInForeground = true;
    }, false);

});
6
  • can i add the $Interval method inside the Pause event, which executes Location fetching task every 5 minutes.. will it work ? Oct 26, 2018 at 5:59
  • This is actually the correct answer to the question
    – Seloka
    Mar 1, 2019 at 13:52
  • @tfmontague: sir can we call watchPosition function is call inside pause event?
    – Kapil Soni
    Mar 14, 2020 at 9:43
  • @ManushVenkatesh - This listens for the "pause" event, and executes some code before the app is paused. Once the app is paused I don't believe it will continue to execute any code. You would need to run your code in a background thread, something like "github.com/katzer/cordova-plugin-background-mode". Mar 15, 2020 at 21:55
  • @KapilSoni - No, this listens for the "pause" event, and executes some code before the app is paused. Once the app is paused I don't believe it will continue to execute any code. You would need to run your code in a background thread, something like "github.com/katzer/cordova-plugin-background-mode". Mar 15, 2020 at 22:11
6

17/09/2019

This works fine for me on Ionic 4 app. Tested both on Android and iOS devices.

app.componet.ts

async initializeApp() {
    await this.platform.ready();

    if (this.platform.is('cordova')) {
        this.setPlatformListener();
   }
 }


  setPlatformListener() {
    this.platform.pause.subscribe(() => {// background
      console.log('In Background');
    });

    this.platform.resume.subscribe(() => {// foreground
      console.log('In Foreground');
    });
  }
5

Using an angular abstraction of ionic.Platform

//The pause event fires when the native platform puts the application
// into the background, typically when the user switches to a different 
// application.
$ionicPlatform.on('pause', function () {
    // Handle event on pause
});
// The resume event fires when the native platform
//  pulls the application out from the background.
$ionicPlatform.on('resume', function () {
    // Handle event on resume
});

Refer to ionic v1 documentation for $ionicPlatform

3

You can also use:

import { Platform, Config, MenuController } from '@ionic/angular';

...

constructor( private platform: Platform)

...

this.platform.resume.subscribe(() => {
      // Handle event on resume
    });


this.platform.pause.subscribe(() => {
          // Handle event on pause
        });
2
0

For those using Capacitor: the App plugin can be used to subscribe to appStateChange events.

For Capacitor v2, import and use the plugin with the following code:

import { Plugins } from '@capacitor/core';

const { App } = Plugins;

App.addListener('appStateChange', (state) => {
  // state.isActive contains the active state
  console.log('App state changed. Is active?', state.isActive);
});

For Capacitor v3+, install @capacitor/app, perform a Capacitor sync (npx cap sync), and then import and use the plugin with the following code:

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

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

Capacitor v4+ provides two additional events called pause and resume that can be subscribed to instead of the appStateChange event:

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

App.addListener('pause', () => {
  console.log('The app was paused');
});
import { App } from '@capacitor/app';

App.addListener('resume', () => {
  console.log('The app was resumed');
});

According to the Capacitor documentation, the appStateChange event depends on the UIApplication.willResignActiveNotification and the UIApplication.didBecomeActiveNotification on iOS devices, whereas the pause event depends on the UIApplication.didEnterBackgroundNotification, and the resume event depends on the UIApplication.willEnterForegroundNotification on iOS devices.

I'm unfamiliar with the specifics of how these events differ, but there certainly does seem to be a difference between them (e.g. see this question).

On Android, the appStateChange, pause, and resume events all seem to depend on the same native events: onResume and onStop.

If you need to check what the current state of the app is without waiting for any of the afore mentioned events to fire, you can use the getState method on Capacitor v2+.

-1
initializeApp() {
  //Subscribe on pause i.e. background or lock phone
       this.platform.pause.subscribe(() => {
          console.log('pause')
      });
  //Subscribe on pause i.e. background or unlock phone
      this.platform.resume.subscribe(() => {
          console.log('resume');
     });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.