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

Sampath
  • 63,341
  • 64
  • 307
  • 441
user1521398
  • 523
  • 1
  • 4
  • 7
  • 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 '15 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 – user1521398 Apr 13 '15 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 '15 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). – tim-montague May 25 '17 at 11:55

9 Answers9

57

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!

Sithys
  • 3,655
  • 8
  • 32
  • 67
  • 1
    Thanks the details example, Sithys – user1521398 Apr 13 '15 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 '17 at 04: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 '18 at 10:42
50

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;
        });
       }
    });
}
Sampath
  • 63,341
  • 64
  • 307
  • 441
Alexander Zakusilo
  • 1,466
  • 3
  • 16
  • 34
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;    
})
George
  • 497
  • 5
  • 15
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);

});
tim-montague
  • 16,217
  • 5
  • 62
  • 51
  • can i add the $Interval method inside the Pause event, which executes Location fetching task every 5 minutes.. will it work ? – Manush Venkatesh Oct 26 '18 at 05:59
  • This is actually the correct answer to the question – Seloka Mar 01 '19 at 13:52
  • @tfmontague: sir can we call watchPosition function is call inside pause event? – Kapil Soni Mar 14 '20 at 09: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 "https://github.com/katzer/cordova-plugin-background-mode". – tim-montague Mar 15 '20 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 "https://github.com/katzer/cordova-plugin-background-mode". – tim-montague Mar 15 '20 at 22:11
  • @tfmontague: thanks for ur response sir but i have already used bakground mode plugin but in my case bakground mode activate function is not fire in background ? – Kapil Soni Mar 16 '20 at 06:06
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');
    });
  }
Sampath
  • 63,341
  • 64
  • 307
  • 441
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

Bugs
  • 4,491
  • 9
  • 32
  • 41
davidbwire
  • 96
  • 2
  • 3
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
        });
Inês Gomes
  • 4,313
  • 1
  • 24
  • 32
  • I tried ur code its working but can i call watchPosition function is call inside pause event? – Kapil Soni Mar 14 '20 at 09:44
  • @Kapilsoni you have to implement a foreground service like https://ionicframework.com/docs/native/foreground-service or background mode https://ionicframework.com/docs/native/background-geolocation – Inês Gomes Mar 16 '20 at 14:02
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+.

Fearnbuster
  • 806
  • 2
  • 14
  • 19
-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');
     });
}