Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  23] [ 6]  / answers: 1 / hits: 57245  / 9 Years ago, mon, april 13, 2015, 12:00:00

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


More From » cordova

 Answers
29

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!


[#67091] Friday, April 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;