Run Ionic 5 Apps in Background using Cordova and Ionic Native plugins

In this Ionic 5/4 tutorial, we’ll learn How to keep the Ionic Application running in the background even when closed or minimized using service with the help of Cordova and Ionic native plugin.

In a native application like android, we have various approaches to keep a service or operation running while the application is minimized or not in the foreground. But in a hybrid application like built-in Ionic framework, we have some limitations to do that as the applications are not that flexible to use background services or any broadcasts attached to some working threads.

In Ionic, luckily we have a Cordova Plugin, which helps in doing this to some extent. We can keep our application in a Running state even if a user minimizes it or moves it in the background.

So here we will implement a plugin BackgroundMode in Ionic’s latest version 5.

Let’s get started!

Supported Platforms

  • Android/Amazon FireOS
  • Browser
  • iOS

 

Install or Update Ionic CLI

Make sure you have the latest version of Ionic CLI installed. Run following npm command to install or update Ionic CLI package globally

$ npm install -g @ionic/cli

 

Create a New Ionic Application

Now create a new Ionic Angular application with a blank template by running the following command

$ ionic start ionic-background-app blank --type=angular
$ cd ionic-background-app

 

Install the Cordova and Ionic Native plugins

Execute the following commands to install required plugins

$ ionic cordova plugin add cordova-plugin-background-mode
$ npm install @ionic-native/background-mode

 

Import native plugin in AppModule

Next, we need to import the plugin class in the app.module.ts

After imports and adding, providers for added plugins file will look like this

// app.module.ts
...
import { BackgroundMode } from '@ionic-native/background-mode/ngx';

@NgModule({
...
  providers: [
    StatusBar,
    SplashScreen,
    BackgroundMode,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Run the Ionic App in Background

Now you need to call backgroundMode.enable() method to enable background service in your application. Here we are calling the enable() method available in the BackgroundMode class after application initialized.

// app.component.ts
import { Component } from '@angular/core';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { BackgroundMode } from '@ionic-native/background-mode/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private backgroundMode: BackgroundMode
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      // Enable Background
      this.backgroundMode.enable();
    });
  }
}

 

Background Configurations Available

The following are the methods and events available to explore in the BackgoundMode class.

  • enable() : void; Enable the background mode. Once called, prevents the app from being paused while in background.
  • disable() : void; Disable the background mode.Once the background mode has been disabled, the app will be paused when in the background.
  • setEnabled(enable: boolean) : void; Enable or disable the background mode.
  • fireEvent(event: string, ...args: any[]) : string; Fire event with given arguments.
  • isEnabled() : boolean; Checks if background mode is enabled or not.
  • isActive() : boolean; Can be used to get the information if the background mode is active. Returns a boolean that indicates if the background mode is active.
  • setDefaults(overrides?: BackgroundModeConfiguration) : void; Overwrite the default settings. Available only for Android platform.
  • configure(options?: BackgroundModeConfiguration) : void; Modify the displayed information. Available only for Android platform.
  • on(event: string) : Observable<any>; Register callback for given event. Available events are `enable`, `disable`, `activate`, `deactivate` and `failure`.
  • un(event: string, callback: (...args: any[]) => void) : void; Listen for events that the plugin fires. Available events are `enable`, `disable`, `activate`, `deactivate` and `failure`.
  • moveToBackground() : void; Android allows to programmatically move from foreground to background.
  • disableWebViewOptimizations() : void; Enable GPS-tracking in the background (Android).
  • moveToForeground() : void; Android allows to programmatically move from background to foreground.
  • overrideBackButton() : void; Override the back button on Android to go to the background instead of closing the app.
  • excludeFromTaskList() : void; Exclude the app from the recent task list. Works on Android 5.0+.
  • isScreenOff(fn: (arg0: boolean) => void) : void; If the screen is off.
  • wakeUp() : void; Turn screen on.
  • unlock() : void; Turn screen on and show app even locked.
  • disableBatteryOptimizations() : void; Disables battery optimization mode for the app (android only).

 

Run Application in Real Device

To check background functionality, you need to run the application in a real device. For that, you need to add the Platform for which you are going to build the application.

Add Platform in Application

Run the following command in the terminal to install the required platform

# Add Android
$ ionic cordova platform add android

# Add iOS
$ ionic cordova platform add ios

# Add Windows
$ ionic cordova platform add windows

 

Build Runnable File

After adding the platform, you can run the following commands to create an executable file like APK file for Android. Or you can simply run the app in the USB connected mobile with USB Debugging enabled discussed in the next step.

# Build Android
$ ionic cordova build android

# Build iOS
$ ionic cordova build ios

# Build Windows
$ ionic cordova build windows

 

Live Run Application in USB connected Device

If you just want to run the application in the real device and debug it on the Chrome browser, just execute the following command after connecting your mobile to your computer

# Live Run on Android
$ ionic cordova run android -l

# Live Run on iOS
$ ionic cordova run ios -l

# Live Run on Windows
$ ionic cordova run windows -l

 

Conclusion

That’s it in this tutorial we discussed how to run the Ionic application in Background using Cordova and Native plugin in an Ionic application. We also discussed how to add platform and test application in a real device to check native features.

If you enjoyed the content. Do share with other geeks. Thanks for reading!

5 thoughts on “Run Ionic 5 Apps in Background using Cordova and Ionic Native plugins”

  1. Hi, this only works when the app is minimized, if you close the app the background task is killed as well

  2. tried calling BackgroundMode.enable, but the BackgroundMode plugin is not installed in ionic 4 how to solve in issue

  3. Just a quick warning to other devs: Katzer’s `cordova-plugin-background-mode` kills the app at launch on iOS 12.2 and 12.3 devices.. Other members have created forks trying to resolve this issue (and a few others), but there are now so many forks to choose from that you’ll never find just one that fixes all of the problems.

    With that said, Ionic’s own `cordova-plugin-ionic-webview` does contain a setting specifically for iOS labelled `WKSuspendInBackground`, if this is set to `false` then the app isn’t suspended when the screen locks and isn’t re-initialised when it’s unlocked again.

Leave a Comment

Your email address will not be published. Required fields are marked *