Prevent Ionic Application From Pausing In The Background

Written by on September 7, 2015

Prevent Ionic Application From Pausing In The Background

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 an 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 Thanks and have a nice day!

Table of Contents


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 the 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
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


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>

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

      // Called when background mode has been activated
      cordova.plugins.backgroundMode.onactivate = function() {
        // if track was playing resume it
        if(trackPlaying) {

      // Start preloaded track'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
        // Audio is no longer playing
        trackPlaying = false;

      }, 1000 * 98);

    // Stop audio function
    $scope.stopAudio = function() {
      // Stop preloaded track

So what’s happening here? When we start audio track playback, we will also initialize the 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


39 thoughts on “Prevent Ionic Application From Pausing In The Background”

  1. Thanks again for the great article.

    I’m going to need this in my app.

    One of the things my app will do is geolocation/tracking (geofencing, sort of) with automatic checkin/checkout of “places”.
    So, this should continue to work when the app is in the background too.

    Likewise, there will be real-time messaging in the app, This should preferably also keep working when the app is in the background, but there I would have the alternative option to use push messaging to “wake up” (activate) the app when there’s a message.

    I think a potential concern with having the app continuously doing stuff in the background would be with battery usage, right? So I suppose one should be a bit careful with this kind of thing.

    • Leo, you’re correct, we need to be very careful using this mode. Battery usage can become problematic but not because of a background mode feature. It’s what we do during this mode that will deplete our battery much faster, like constant GPS checks, or server pinging for real-time messaging apps.

      Do you mind if we stay in a contact.? I would like to discuss how you’re going to implement background geolocation. Using this plugin or using a background geolocation plugin?

      • Yeah sure, interesting to discuss our findings when I’m a bit further with the project.

        Yes I’ve heard about the geolocation background plugin, but it’s good that you mention it before I forget.
        I need to look at that plugin as well.

        On the other hand probably I want to handle messaging in the background too, but maybe that’s best solved by combining it with push notifications.

        Anyway let’s see, as always it’s a matter of experimenting and seeing what works best.

        • Super interested in how you handled geolocation in the background. It looks like geolocation background plugin is a pay for product.

          Would you mind sharing a little information as to what you did? I’m doing essentially the same thing.

          • Yeah well in the end I didn’t implement the fancy background geolocation stuff, it was a little bit of overkill for the MVP (Minimum Viable Product) that we were building.

            So we ended up implementing the geolocation in a very simple way, when a customer “checks in” in the app we just ask the coordinates at that moment. So at this stage there was no need for continuous realtime position tracking in the background (yeah that plugin is paid/commercial and it’s quite expensive so not really an attractive option to me).

            The messaging stuff does need to “run in the background” but for that we just use Push Messaging which works even when the app isn’t running and which can also “wake up” the app when a push message arrives.

          • Thanks for the info. I’ve found push notifications definitely work. The real-time tracking seems a little invasive too. We’re going a different direction as well.

          • Hello James
            I’m facing issue while implementing the push notifications in my ionic application.
            Can you please help me out.

            If any steps are there for implementing push notifications please share with me.

      • Hi Leo and Dragan,
        I want to know is there any plugin available for mobile data usage analysis for applications which are installed on the mobile device…………
        Thanks in advance.

      • Hello Dragan and Leo,
        I just read conversation for background geolocation/ GPS tracking. I tried different ways to update geolocation in background mode at server side. But enable to get result. Everything works fine when app is in foreground mode and in android when app is in background mode background location gets updated at server side. But problem comes at iOS platform in background mode. It will be helpful if you can provide article like audio for same(background geolocation).

  2. Thank you very much for the tutorial, I’ve been very impressed with the ones you’ve written.

  3. Hi, is there is any plugin can listen to volume up or down and for some count it will send SMS in background

  4. Dear, I made the tutorial and it has worked only for devices with less than 5.0 android from 5.0 onwards the background mode does not work. what should I do?

  5. The GitHub page says this plugin will get your app rejected in “certain” stores. From further reading I’ve found several reports of Apple rejecting apps specifically for this plugin. It would appear that you need to justify the need for it, and they can easily just say no. Certainly there are apps in the Apple store that do run in the background, so ymmv.

  6. Hi there. First of all, thanks a lot. It worked pretty well on my Android 5.0. I will try on iOS. Thanks

    • It worked pretty well in Android and iOS. I tried with audio plugin and also with $cordovaGeolocation (using

  7. Hello

    First of all many thanks for this tutorial.

    We are trying to implement a video recording app using +Ionic, and one of the show-stopper issue we are facing is how to disable the pause button on android phones using codoba Camera pluging. In fact once the video recording starts we want to prevent the user from pausing the recording and continue later.

    Do you have any idea if this is possible by any mean using ionic ? Your example is talking about playing the video If I got it right. Is the same thing possible while recording ? We haven’t found any event to handle in our case :S Any idea ?


      • Thanks for your instant reaction on this Marcos, Can you please guide me on this as we are not getting approval on this, they are saying same thing regarding plugin that “Please revise your app to provide audible content to the user while the app is in the background or remove the “audio” setting from the UIBackgroundModes key.”
        Your guidance will be valuable for us.

        Many Thanks!

  8. hi,

    I try to follow the step and I’ve successfully build the app. However, when I click the PLAY button the music don’t play. I create folder name AUDIO inside of WWW folder and put my mp3 file.

  9. Hello … Can the same be implemented for tracking the GPS location if the application is in background ???

  10. Can you please put the ionic version on your article… you’re waisting people time reading useless info

  11. Hi, thank you i ran this demo successfully. I want to use this idea for popup notification for daily usage. Like app will call an API after every few hours , get results and display to user as popup message. For popup dialog i am using “cordova-plugin-dialogs”.
    When user first time open the app i will enable the background, if user close the app from app list, background on activate will have a timer which will call API after few hours, if data is there it will show popup. Please can you advise if this is suitable and possible, also timer in background will run for whole time, is it OK? FYI app is used internally by couple of hundred people, but will be on play store.

      • Just saw the methods for background plugins, now updated code as following:
        cordova.plugins.backgroundMode.overrideBackButton(); //this is not working dont know why
        cordova.plugins.backgroundMode.excludeFromTaskList(); // this works

        • ok now i used this function to prevent back button, and its working fine.
          $ionicPlatform.registerBackButtonAction(function (e) {
          }, 1000);

          • any one having same scenario like me use one signal, push notification is better, and you can simply call their api from your server side.

Leave a Reply