34

Is it possible to run a background service if I close my Ionic/Cordova app (both for iOS and Android) ?

For the purpose I picked that pluging https://github.com/katzer/cordova-plugin-background-mode

So far I have that code:

$ionicPlatform.ready(function () {
            cordova.plugins.backgroundMode.isEnabled();

            cordova.plugins.backgroundMode.configure({
                silent: true
            }) 
              ............
            ///do some task
)}

It works fine if the app goes to the foreground but as soon as I close the application the task I am running stops as well. So is there any workaround/way to make my task running even if the app is closed ?

EDIT:

I have also added permissions for both iOS and Andorid but I am getting the same result.

EDIT 2:

What am I trying to do in background is to write my own implementation of significant location-change service since there is no free plugin for Cordova or PhoneGap that can work with both iOS and Android.

theDmi
  • 17,546
  • 6
  • 71
  • 138
radioaktiv
  • 2,437
  • 4
  • 27
  • 36

3 Answers3

14

Ionic Framework

I've recently implemented a feature like this in my project. I did use Ionic and I did use the Cordova plugin background mode from Katzer. (right now I'm running the background process through the iOS 9.2 simulator).

Here's a code snippet to get it working:

// Run when the device is ready
document.addEventListener('deviceready', function () {

    // Android customization
    // To indicate that the app is executing tasks in background and being paused would disrupt the user.
    // The plug-in has to create a notification while in background - like a download progress bar.
    cordova.plugins.backgroundMode.setDefaults({ 
        title:  'TheTitleOfYourProcess',
        text:   'Executing background tasks.'
    });

    // Enable background mode
    cordova.plugins.backgroundMode.enable();

    // Called when background mode has been activated
    cordova.plugins.backgroundMode.onactivate = function () {

        // Set an interval of 3 seconds (3000 milliseconds)
        setInterval(function () {

            // The code that you want to run repeatedly

        }, 3000);
    }
}, false);

Ionic Framework 2

Here's an Ionic 2 example ES6 ready:

// Import the Ionic Native plugin 
import { BackgroundMode } from 'ionic-native';

// Run when the device is ready
document.addEventListener('deviceready', () => {

    // Android customization
    // To indicate that the app is executing tasks in background and being paused would disrupt the user.
    // The plug-in has to create a notification while in background - like a download progress bar.
    BackgroundMode.setDefaults({ 
        title:  'TheTitleOfYourProcess',
        text:   'Executing background tasks.'
    });

    // Enable background mode
    BackgroundMode.enable();

    // Called when background mode has been activated
    // note: onactive now returns an returns an observable that emits when background mode is activated
    BackgroundMode.onactivate.subscribe(() => {
          // The code that you want to run repeatedly
    });
}, false);
0x1ad2
  • 8,014
  • 9
  • 35
  • 48
  • And that works even if you completely close the app ? – radioaktiv Dec 14 '15 at 14:01
  • If you close the app as in "move it to background" it will work. – 0x1ad2 Dec 15 '15 at 08:07
  • What if the person turns off the phone ( I mean a complete shutdown and restart ), then what would it it take to put your code back into the game? I know that all Alarm apps achieve that. – Average Joe Jan 05 '16 at 00:47
  • @AverageJoe I think that's nearly impossible or you need to write values to memory that's kept after restarting or another data source like a NoSQL database. – 0x1ad2 Jan 05 '16 at 07:49
  • 1
    Since alarm apps can do that, I suspect that there must be a way. I just tried this on my android phone; 1) set up an alarm 3 min for later. 2) Power the phone off completely. 3) And boot it and then boom, that alarm I set 3 min ago kicked in. ( At that time, the alarm app was not among the "running apps" but the alarm itself was able to fire. ) – Average Joe Jan 09 '16 at 02:11
  • I think that is because the alarm clock app must be set to launch in the background when the device is booted. Similar to startup apps in windows. – Mikecit22 Feb 22 '16 at 21:30
  • @0x1ad2 I tried the code as well on ionic with Iphone. Do I just put the code in $ionicPlatform.ready(function(){}? Anything else? – UniSound Waterloo Feb 26 '16 at 01:59
  • @UniSoundWaterloo has been a couple of months so I'm not sure if it still works but I would try to put the code inside a controller. https://github.com/katzer/cordova-plugin-background-mode – 0x1ad2 Feb 26 '16 at 11:31
  • Hi.. I used the same plugin. but when i open other app, my app is not working in background. Also it restarts on opening. Please let me know if i am missing anything. Thanks in advance – AishApp Aug 11 '16 at 11:31
  • Can We trigger localnotification ... ?? – Gopinath Kaliappan Oct 28 '16 at 02:44
  • Does this work if I close the app like Whatsapp? As in press the home button and clear all recent apps in android. – David Christie Jul 01 '19 at 10:13
2

I think the background geolocation tracking that you're trying to implement already exists as a cordova plugin, it's called cordova-plugin-mauron85-background-geolocation.

This plugin is both a foreground and background geolocation service. It is far more battery and data efficient then html5 geolocation or cordova-geolocation plugin.

There are a lot of configuration options, see the github page linked above.

theDmi
  • 17,546
  • 6
  • 71
  • 138
0

Workaround on IONIC-3

import the plugins

import { Platform } from 'ionic-angular';
import { BackgroundMode } from '@ionic-native/background-mode';

add in constructor

constructor(private backgroundMode: BackgroundMode, private plt: Platform) {
    this.initBackgroundMode();
}

private initBackgroundMode() {
    this.plt.ready().then(() => {
        this.backgroundMode.setDefaults({ silent: true });
        this.backgroundMode.enable();
        if (this.plt.is("android")) {
            this.backgroundMode.on('activate').subscribe(() => {
                this.backgroundMode.disableWebViewOptimizations();
                // Custom code for updating the location 
                // or do similar functionality
                // use timeout or interval accordingly to execute the functionality in loop
            });
        }
    })
}
Jose G Varanam
  • 767
  • 8
  • 19
  • Does this work, if your app is closed and NOT running in background?! – Rebar Mar 31 '18 at 18:44
  • @Rebar Background activity will happen only when the app is in the background. Above code won't support on a killed app or NOT running in the background. – Jose G Varanam Apr 02 '18 at 10:15