Last few months I noticed one thing, a lot of developers don’t understand what’s happening with an application when it’s paused in the background.
 
Let’s assume we have an application that can’t handle background mode. When you hide such application, it will pause its execution. Everything will freeze, including music/video playback, GPS tracking, etc.
 
We can counter it using Cordova Background mode plugin, and this is going to be the main point of this tutorial. To make it clear, we’ll create a simple audio player, so you’ll also learn how to use Cordova Native Audio plugin. Why audio player, especially if some of you would rather see a background GPS example? There’s a good reason; this mode has a small catch, and we can notice it only during audio or video playback. You see, this plugin will not prevent an application from freezing, it will hijack it instead. During this process, an application will freeze for a moment, just enough to hear a noticeable audio pause.
 
Beyond audio playback, this mode is also usable in some other cases (info thanks to Leo van den Bulck):
 
  • Geolocation/Tracking (now even more important since Background Geolocation plugin is no more available)
  • Real-Time Messaging
  • Local Notifications
  • Streaming services
 
 

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!
 

Table of Contents

 
 
Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)

Tutorials

Other Resources (themes, templates, plugins, Cordova plugins, starter apps)

Cordova Plugin Tutorials

 

Preparation

 
This tutorial requires a preconfigured environment. Skip this step if you already have this covered.
 
  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
If you don’t have previous Ionic Framework experience, find more information here: Ionic Framework | Installation Guide.
 

1. Update Ionic & Cordova

 
Before we can start make sure you have the latest nodeJS installation, without it, you’ll not be able to install Ionic and Cordova properly.
 
If everything went well with nodeJS, let’s continue with Ionic and Cordova:
 
npm update -g cordova ionic
 

2. Create a New Project

 
ionic start IonicBackgroundMode blank
cd IonicBackgroundMode
 
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.
 
This example requires Android platform:
 
ionic platform add android
 
For MacOS users, do it like this:
 
ionic platform add ios
 

4. Install Cordova Background Mode and Native Audio plugin

 
Add these:
 
cordova plugin add cordova-plugin-nativeaudio
cordova plugin add https://github.com/katzer/cordova-plugin-background-mode.git
cordova plugin add cordova-plugin-whitelist
 
We will not use ngCordova wrapper for Native Audio plugin. For some reason, I’m having problems using it with a local content, so I’m sticking with the original implementation.
 
If you’re using Cordova 4.0 or higher, you will need to install Whitelist plugin. Without it you’ll receive “Application Error: There was a network error.” error.
 
GitHub - Background Mode GitHub - Native Audio
 
 

Development

 
At this point, you should have everything set up and ready, we can start working on our example.
 
Open index.html file, add a controller to ion-pane directive:
 
  <ion-pane ng-controller="BackgroundController">
      <ion-header-bar class="bar-stable">
        <h1 class="title">Background App Example</h1>
      </ion-header-bar>
      <ion-content>
      </ion-content>
   </ion-pane>
 
Initialize BackgroundController controller in a app.js file:
 
app.controller('BackgroundController', function($scope) {

});
 
If you’re using Cordova 4+, you will need to check if there’s a Whitelist plugin installed with your project. If you have it, add this security meta tag to your index.html HEAD content:
 
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
 
Without it your application will throw an error during the app initialization, after that it will continually throwing no security meta-tag found. While not a blocking point, constant console log warnings will make it hard to do any debugging.
 
Both plugins require Cordova or Ionic ready event, so don’t forget it:
 
document.addEventListener('deviceready', function() {
   // Rest of the code
});
 
During the application initialization, we’re going to preload an audio track (use any audio track you want):
 
    window.plugins.NativeAudio.preloadComplex('music', 'audio/The_Master.mp3', 1, 1, 0, function(msg) {
      console.log('msg: ' + msg); // Loaded
    }, function(msg) {
      console.log('error: ' + msg); // Loading error
    });
 
These two functions will provide stop and play audio features:
 
    $scope.playAudio = function() {

      // Enable background mode while track is playing
      cordova.plugins.backgroundMode.enable();

      // Called when background mode has been activated
      cordova.plugins.backgroundMode.onactivate = function() {
        // if track was playing resume it
        if(trackPlaying) {
          window.plugins.NativeAudio.play('music');
        }
      }

      // Start preloaded track
      window.plugins.NativeAudio.play('music');
      trackPlaying = true; // Track is playing

      // Stop multichannel clip after 98 seconds, provided track runs for 1:38 min
      window.setTimeout(function() {

        window.plugins.NativeAudio.stop('music');    // Stop audio track
        window.plugins.NativeAudio.unload('music');  // Unload audio track and save memory

        // disable application if we're still in background and audio is no longer playing
        cordova.plugins.backgroundMode.disable();
        
        // Audio is no longer playing
        trackPlaying = false;

      }, 1000 * 98);
    };

    // Stop audio function
    $scope.stopAudio = function() {
      // Stop preloaded track
      window.plugins.NativeAudio.stop('music');
    };
 
So what’s happening here? When we start audio track playback, we will also initialize background mode. If we hide our application, an audio track will pause playing. At the same time, background mode will trigger onactivate event thus resuming audio play.
 
SetTimeout function will stop and unload audio track after 98 sec (a full length of provided audio track). If we’re still in the background, setTimeout will also disable background mode, thus again freezing our application.
 
Let’s sum this up:
 
  • Audio track is preloaded on application initialization
  • Variable trackPlaying is set to false (false -> audio is not playing, true -> audio is playing)
  • At this point we don’t need background mode, even if aplication is paused it’s still not doing anything
  • When audio track starts playing (on button click), application will trigger background mode, this way audio will play in tha background
  • Variable trackPlaying is set to true, audio is playing
  • Application is binding an onactivate event including everything that needs to be done during this mode.
  • Timer is executed. It will stop and unload audio track after 98 sec which is a length of provided audio track in my example.
  • Timer will also disable background mode when audio tracks stops playing
  • If we hide our application it will trigger onactivate event
  • Event will check if audio was playing (trackPlaying variable). If yes it will resume audio track.
Continue to the next page