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

JavascriptCordovaIonic FrameworkIonic3Ionic4

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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!

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

    });

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1521398View Question on Stackoverflow
Solution 1 - JavascriptSithysView Answer on Stackoverflow
Solution 2 - JavascriptAlexander ZakusiloView Answer on Stackoverflow
Solution 3 - JavascriptGeorgeView Answer on Stackoverflow
Solution 4 - Javascripttim-montagueView Answer on Stackoverflow
Solution 5 - JavascriptSampathView Answer on Stackoverflow
Solution 6 - JavascriptdavidbwireView Answer on Stackoverflow
Solution 7 - JavascriptInês GomesView Answer on Stackoverflow
Solution 8 - JavascriptJitendra DhadaviView Answer on Stackoverflow