How to run cordova plugin in Android background service?

I am working on mobile application developed on cordova . I want to implement a background service that do some work like open socket connection syncronise local database with remote one and notify the users on new remote pushes etc . The point is I have this code implemented in javascript but I want execute it i background.

I searched internet for a cordova background service plugin.

The best one I think is red-folder but it is just for android and it does not let me to write javascript to be executed in background. but just exchange json between java and javascript.

I have read some topics about background service in android these are useful ones I found:

So I started writing cordova plugin (primarily on android) to execute the javascript code in background. I created a webview from the background service to execute the javascript from it. This works fine when I execute normal javascript but when it comes to cordova plugins js it fails for example the device device.uuid gives null.

This is the java service code:

      public void onStart(Intent intent, int startId) {
   	  Toast.makeText(this, "My Happy Service Started", Toast.LENGTH_LONG).show();
       
           createBackGroundView();
           super.onStart(intent,startId);
    }


      public void createBackGroundView(){

         
        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
       LayoutParams params = new WindowManager.LayoutParams(
                   android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                   android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                   WindowManager.LayoutParams.TYPE_PHONE,
                   WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                   PixelFormat.TRANSLUCENT
           );
         
        params.gravity = Gravity.TOP | Gravity.LEFT;
        params.x = 0;
        params.y = 0;
        params.width = 200;
        params.height = 200;
       
        LinearLayout view = new LinearLayout(this);
           
        view.setLayoutParams(new RelativeLayout.LayoutParams(
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT, 
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT
            ));
           
        WebView wv = new WebView(this);
        wv.setLayoutParams(new LinearLayout.LayoutParams(
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT
            ));     
        view.addView(wv);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setWebChromeClient(new WebChromeClient());
            wv.loadUrl("file:///android_asset/www/background.html");
        wv.setWebViewClient(new WebViewClient() {

			@Override
			public void onReceivedError(final WebView view, int errorCode,
					String description, final String failingUrl) {
				Log.d("Error","loading web view");
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
		});

        windowManager.addView(view, params);
  
     }

Update
There is no error in the logcat.
So I tried to write the device object on the screen and thats what I get :

  document.write(JSON.stringify(window.device))

And this is the result :

  { available : false, 
    plaform : null , 
    version : null , 
    uuid : null ,  
    cordova : null ,
    model : null 
   }

Any help about this problem ?

2 Likes

+1
No solution here but I’m very curious to see one!

There is no direct support for background service in Phonegap/Cordova apps.
The reason is that your hybrid app is written in JS, and your JS code runs in an Activity that has a webview.
As soon as you exit your app, the app is suspended.

If you really want to have background service in android, you can write your Android service in Java (native) and call your service from your JS code. (Native for background service & JS for your app)

This link might help you:

@mehsen - I had some luck with using https://github.com/katzer/cordova-plugin-background-mode on https://github.com/brentvatne/pacer for geolocation polling in the background, just set a timeout and called window.plugin.backgroundMode.enable(); and it worked.

1 Like

Hi Brent
I implement cordova plugin background mode, I do following step
cordova add plugin …
import background-mode.js at index html
at app.js

 $ionicPlatform.ready(function() {
           ......
    	window.plugin.backgroundMode.enable();
      });

But when run ionic serve, I got error Cannot read property 'backgroundMode' of undefined
Tell me where I go wrong, thanks

1 Like

Could you explain what different between background-mode vs background service

@mehsen

Have you implement background service working ?
I can not make push notification work on when phone screen off after a few minutes

Hi @nvcken - that is because the plugin will only work when you run the app on your device, using something like ionic run android

@brent
I use ionic run android to test app on my android device.
could you tell me more advance?

Hi Brent,

Can you share a sample of your code? I also want to do geolocation polling in the background.

Did you find any solution for background service of push notification?

Any solution ? I stuck with the same problem

You should call it using window:

window.cordova.plugins.backgroundMode.enable()

Hello,
Firstly you have to install the Cordova in Ionic native plugins:
$ ionic cordova plugin add cordova-plugin-background-mode
$ npm install --save @ionic-native/background-mode

Add this plugin to your app’s module

After that, you have to import the component, just pass it to the constructor of the component you want to run in the background like:

import { BackgroundMode } from ‘@ionic-native/background-mode’;

constructor(private backgroundMode: BackgroundMode) { }

this.backgroundMode.enable();

Contact with http://www.habilelabs.io/ for more.

Thanks