Ionic 4 | Keep It Running in Background using Cordova and Ionic Native plugins

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 limitation to do that as the applications are not that much 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 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 4. Ionic 4 is still in beta phase, but it will be released soon for development.

Let’s get started!

First, we will create a new Ionic 4 Application

Make sure you have NodeJS and latest version of Ionic CLI installed

Run the following command to create a new Ionic 4 Application

Install the Cordova and Ionic Native plugins

 

Import native plugins in app.module.ts

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

 

Now you need to call  backgroundMode.enable() method to enable background service in your application.

Here we will call this method in the Application Component to start it on application start.

Now you can run the application in a real device. Create a debug apk for Android by running

This plugin will keep the app running in the background.

Similarly, we can disable BackgroundMode by calling this method

To check if BackgroundMode is active we can run the following method

You can check more events available here .

 

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

3
Leave a Reply

avatar
2 Comment threads
0 Thread replies
3 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
amineJaydeep Rathod Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jaydeep Rathod
Member

how to use this backgroundMode.isActive();??

amine
Guest
amine

this will not work in android 8+

Andre Greeff
Guest
Andre Greeff

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.