There will often come a scenario where you need to determine when your application enters the device background and comes back into the foreground. For example, let’s say we wanted to require a password every time the application is shown. We would need to listen for when the application enters the foreground.
Lucky for us, we can make use of the Apache Cordova event listeners to accomplish this task.
Apache Cordova events require no additional plugin installation for Ionic Framework. To register an event we must do so in our $ionicPlatform.ready()
method. For example, we might have register something that looks like this:
var exampleApp = angular.module('example', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
document.addEventListener("resume", function() {
console.log("The application is resuming from the background");
}, false);
});
});
In the above example, a resume
listener is registered. Every time the application regains focus, the callback function will run printing information to the log.
There are many different listeners that can be registered, but according to the Cordova documentation only the following work for Android and iOS. At the time of writing this article, Ionic Framework 1.0.0 beta 11 only supports Android and iOS.
Listener | Description |
---|---|
resume | The resume event fires when the native platform pulls the application out from the background. |
pause | The event fires when an application is put into the background. |
online | This event fires when an application goes online, and the device becomes connected to the Internet. |
offline | The event fires when an application goes offline, and the device is not connected to the Internet. |
It is important to note that this can only be tested from a device or simulator. The web browser will not recognize these listeners.
A video version of this article can be seen below.