user1521398
user1521398

Reputation: 533

how to check app running in foreground or background in ionic/cordova/phonegap

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

Upvotes: 53

Views: 60503

Answers (9)

Fearnbuster
Fearnbuster

Reputation: 896

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

Upvotes: 0

Sithys
Sithys

Reputation: 3803

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!

Upvotes: 59

Jitendra Dhadavi
Jitendra Dhadavi

Reputation: 85

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');
     });
}

Upvotes: -1

Sampath
Sampath

Reputation: 65978

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');
    });
  }

Upvotes: 6

Alexander Zakusilo
Alexander Zakusilo

Reputation: 1566

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;
        });
       }
    });
}

Upvotes: 54

In&#234;s Gomes
In&#234;s Gomes

Reputation: 4851

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
        });

Upvotes: 3

tim-montague
tim-montague

Reputation: 17442

"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);

});

Upvotes: 9

davidbwire
davidbwire

Reputation: 96

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

Upvotes: 5

George
George

Reputation: 507

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;    
})

Upvotes: 13

Related Questions