Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Monitor Device Battery Status Using Ionic Framework

TwitterFacebookRedditLinkedInHacker News

So you’re making a mobile app using Ionic Framework and you care about the experience your users receive? Maybe you want to control the functionality of certain features based on how much battery the users device has left.

An example of this is, maybe you have your application pulling remote data while the application is open. Maybe you’ve decided that if your users battery is less than 30% you want the user to have to pull-to-refresh in order to preserve battery life.

This kind of battery monitoring can be performed through the cordova-plugin-battery-status plugin by Apache Cordova.

Let’s go through using this plugin by first creating a fresh Ionic Framework project via your Terminal or Command Prompt:

ionic start IonicProject blank
cd Ionic Project
ionic platform add android
ionic platform add ios

Remember, if you’re not using a Mac, you cannot add and build for the iOS platform.

With the project as your current working Command Prompt or Terminal directory, enter the following in order to install the battery status plugin:

cordova plugin add cordova-plugin-battery-status

We aren’t going to use the plugin in its raw JavaScript form. Instead we’re going to use the AngularJS extension set, ngCordova, to make things a little more Ionic Framework friendly.

The ngCordova library changes frequently, so for this tutorial, we’re going to use commit c3634c64 from GitHub. Feel free to be adventurous and use the latest, but don’t be too surprised if this tutorial doesn’t work with it.

After downloading ngCordova, place the ng-cordova.min.js file in your project’s www/js directory and add it to your www/index.html file like so:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>

        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">

        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
        <link href="css/ionic.app.css" rel="stylesheet">
        -->

        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.js"></script>

        <!-- cordova script (this will be a 404 during development) -->
        <script src="js/ng-cordova.min.js"></script>
        <script src="cordova.js"></script>

        <!-- your app's js -->
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter">
        <ion-pane>
            <ion-header-bar class="bar-stable">
                <h1 class="title">Ionic Blank Starter</h1>
            </ion-header-bar>
            <ion-content ng-controller="ExampleController">
            </ion-content>
        </ion-pane>
    </body>
</html>

Notice that I’ve placed ng-cordova.min.js above cordova.js. This is important because if you don’t, you’re going to get strange results.

Also take note of ng-controller="ExampleController" found in the <ion-content> tags. We’re going to create that controller now.

Open your project’s www/js/app.js file and make it look like the following:

angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if(window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
})

.controller("ExampleController", function($scope, $rootScope, $ionicPlatform, $cordovaBatteryStatus) {

    $ionicPlatform.ready(function() {
        $rootScope.$on("$cordovaBatteryStatus:status", function(event, args) {
            if(args.isPlugged) {
                alert("Charging -> " + args.level + "%");
            } else {
                alert("Battery -> " + args.level + "%");
            }
        });
    });

});

We’ve injected ngCordova into our module and created our controller code. Because we’re using a plugin that makes use of native device code, we need to wrap it in an $ionicPlatform.ready function. You can use onDeviceReady if you’d prefer as well. This will tell your code to wait until the Apache Cordova plugins are ready before trying to use them.

The ngCordova plugin broadcasts information regarding the battery on three channels:

  1. $cordovaBatteryStatus:status
  2. $cordovaBatteryStatus:critical
  3. $cordovaBatteryStatus:low

In the above code, we’re only listening on the status channel. Every time the battery percent changes by at least one, it will be called and display an alert.

Conclusion

Monitoring device battery life can have many advantages in your mobile application and can easily drive a better user experience. Using the battery status plugin in your Ionic application could bring good things with minimal effort.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.