implementing long running background tasks in phonegap - android

I am trying to run a snippet of javascript which keeps polling the server for updates. what is the best way to get this working with minimal impact on application performance from the end user perspective.
I tried spawning it off in a separate iframe but the resultant performance was pretty bad.
I am currently working on android so if the solution involves writing a phonegap plugin to poll the server instead of javascript that should be fine for now. I need to update data in local storage after polling the server.

I have implemented this in IOS. The problem with phonegap is that you can't create a timer task that runs javascript because if your .html page changes the task would be killed.
Unless you just have ONE .html and you are dynamically changing the body part. If that is the case then look up setInterval in javascript.
If that isn't the case then implementing something on javascript isn't a solution, in IOS I have implemented a custom plugin for running asynchronous web service calls. You could do something similar, writing a plugin that runs a AsyncTask doInBackground() and then postback the results in the javascript. There are many tutorials on how to create a custom plugin in phonegap. Hope it helps

If you are planning to poll only when the application is in use the setInterval() works fairly well. My application is using jQuery Mobile which by default only updates DOM rather reloading entire page, that way my setInterval() keeps running once started.
Android already has a support of Background services, which you can use for the long and continuous running tasks.
One solution which I have used with above combination:
when the app is running I use setInterval() to check for update periodically.
Background checks whether application is running or not before starting the update checks
If the app is not running then I use the background service code just to check whether there are any updates on server or not
If there are updates then I put a system tray notification to notify user that there are updates waiting for him
As soon as he starts the application, I call the service to fetch the updates.
This way my main logic remains in the Javascript side and I need not to write same logic in both Javascript and native again.
If updates are not very frequent then you should consider using PushNotification

Related

How to use service workers in Cordova Android app?

I want to use a service worker in my Cordova Android add as a convenient way to sync some images to and from the server. I notice that this question states that this is not possible, since service workers must be loaded via https:, whereas Cordova will load files via file:.
On the other hand, it seems that ionic supports service workers. That implies that they have figured out some way to make this work. However, I am not using ionic. There appears to be a cordova plugin for service workers for iOS, but as I said I am on Android.
What is the current best practices for using service workers in Cordova Android apps, if that's possible at all?
After digging deep into this issue, I conclude that there is no support for Service workers in Android as it blocks service workers from HTTP or file protocols.
Also the support of Service worker in Ionic framework do not clearly state that it is not supported in hybrid mobile apps. It's kind of misleading too as in this case. Ionic's Service Worker support comes into picture only in case of Progressive Web App and not in hybrid mobile app as mentioned in their official blog
Adding to the above info, most of the functionality that can be achieved by using Service Workers are already available as part of plugins like push notification plugin which should be suffice in most cases.
The bottom line is that the Service Workers are not supported in Cordova Android as well as in Ionic framework. For more info, check out the following link
I couldn’t take “no” for an answer so went on a hunt to see if I could code my way out of this.
Note, I'm not sure I was having the same issue or even had the same req as the OP (apologies if not, but hopefully it was)... my scenario was this, for clarity
I had initial luck with manually fetching and adding items (https://localhost/cordova.js and the plugin files) to the cache the Service Worker uses. I did this on first run up and the 2nd run up (even if offline) worked… so some good progress. Weirdly on subsequent run ups some (most) of the manually cached items were removed and so startups did not complete successfully.
I then looked into if I could bypass the SW completely for calls to localhost, and what do you know, it seems to work. Essentially in the SW’s fetch handler I have a conditional clause to do nothing if it spots localhost in the url. This has the affect that SW can’t find a fetch handler that takes care of the request and then the browser makes the call to fetch the asset just as if there were no SW at all.
I have tested this for both online/offline starts, and made sure I can access cordova and some of the plugins, and all seems to run just fine. Note, all testing so far is on Android.
An example of the code I used is as followa (left an explicit “do nothing” comment in for clarity);
self.addEventListener('fetch', event => {
console.log('Fetch event for ', event.request.url);
if (event.request.url.includes("localhost")) {
// Do Nothing
} else {
event.respondWith(
caches.match(event.request, {
// ... do the rest of the SW handling
I’d be interested to hear if other folk had tried this and then had any issues with it.

Download data from webview when the app is closed

Hi I'm writing an android app which has to retrieve some infos from a website using webview and js, I figured out how to do that when app is opened, is there a way to get these infos when app is closed? Almost like whatsapp and gmail do...
You're not going to be able to use a WebView when the app isn't showing. What you can do is use a service, which runs in the background, there you can make requests to download data over the Internet.
More info
http://developer.android.com/guide/components/services.html
Keep in mind that your standard service will run on your applications main thread, so you may need to provide threading for yourself.
To make your code trigger at a given time checkout alarms:
http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html
For non WebView web browsing consider:
Use V8 JavaScript engine to execute JS lib without webview
You will need to run your logic on a service.
The service will run on the background and do your app logic.
If you app is doing CPU intensive operations, run your service on another thread. Read the official documentation of services for more information on how to use them.

build.phonegap.com - background process (task to complete at regular intervals whether app running or not) [duplicate]

I have been working on an Android app using Phonegap and now would like to make it so when the app is closed it can still execute the java/js code in the app. So I understand I need to create a service. If I create a service plugin on phonegap can I still execute the javascript code or only the java?
Has anyone does something like this? I found this discussion but did not seem to work: http://groups.google.com/group/phonegap/browse_thread/thread/722b0e796baa7fc6
So that is all I have right now.
Before I turn to developing it native if I can't figure it out thought I would ask if anyone has done this before. I can't seem to find any of the phonegap plugins that do something similar.
EDIT: I have got an app that executes Java code as a service. However when it calls sendjavascript it does not work. So is there a way to have the javascript code running in the background as well when an app is closed with phonegap?
Thanks
No, it is not possible to run Javascript code in the background (at least in my opinion) as a service. Phonegap on Android uses an special activity called Droidgap, which hosts a WebView. This browser control executes the JavaScript. This means that JS execution can only handled inside this activity, regardless if it is visible or not.
The code you linked from Google Groups tries to bind a service developed in Java to the DroidGap activity, so the service is NOT written in JS.
You can have some background activity within your JS code inside your child activity derived from the DroidGap activity. For example have a background thread in your activity, have a JS callback function and let the thread call this callback functionality.
If you really need a service you have to go native.
Update:
JS code can only be executed with the Droidgap activity. An activity can have 3 states (based on the Lifecycle of activites):
visible
invisible but still loaded
not loaded
I provided a sample in which I implemented a Phonegap plugin. The plugin allows the activity to register itself to SMS_RECEIVED. When the activies goes out of scope (event onbeforeunload), it deregisters, so only issue 1 is handled.
When you want all 3 issues handled, you have to forward the incoming SMS intent to the activity. When it is not loaded the system will automatically load and activate the activity. But this is not a background service anymore, your app would become visible whenever a SMS is received.
If you don't want this (if you really want a background service), you have to provide a native implementation.
There is this article on how to create a service on Android with Phonegap which gives some good information on your problem.
It's using a great plugin in order to build a background service with phonegap easily. But you can't use JS though
I didn't find a way to make JS to run in the Background. BUT you can pass parameters from Java to JS and vice versa with the plugin...which is pretty useful.
You would still need to rewrite your JS code in Java though.
Unless you do have a specific reason to only want JS to be run? (But there shouldn't be...)
Hope that could be useful to some people visiting this page.
YES, and it is very simple... just install the plugin backgroundJS:
https://build.phonegap.com/plugins/430
It allows you to run javascript on the background and combined with the local notification plugin, you can even send notifications to the user at any time, just keep in mind that doing this will cause the battery to run out faster, also consider that this might create a problem with the iOS policy. good luck!!!
You can try to add plugin cordova-plugin-background-mode
But as author says:
Infinite background tasks are not official supported on most mobile operation systems and thus not compliant with public store vendors. A successful submssion isn't garanteed.
Use the plugin by your own risk!

Creating an Android Service with Phonegap? (Have phonegap app run even when closed)

I have been working on an Android app using Phonegap and now would like to make it so when the app is closed it can still execute the java/js code in the app. So I understand I need to create a service. If I create a service plugin on phonegap can I still execute the javascript code or only the java?
Has anyone does something like this? I found this discussion but did not seem to work: http://groups.google.com/group/phonegap/browse_thread/thread/722b0e796baa7fc6
So that is all I have right now.
Before I turn to developing it native if I can't figure it out thought I would ask if anyone has done this before. I can't seem to find any of the phonegap plugins that do something similar.
EDIT: I have got an app that executes Java code as a service. However when it calls sendjavascript it does not work. So is there a way to have the javascript code running in the background as well when an app is closed with phonegap?
Thanks
No, it is not possible to run Javascript code in the background (at least in my opinion) as a service. Phonegap on Android uses an special activity called Droidgap, which hosts a WebView. This browser control executes the JavaScript. This means that JS execution can only handled inside this activity, regardless if it is visible or not.
The code you linked from Google Groups tries to bind a service developed in Java to the DroidGap activity, so the service is NOT written in JS.
You can have some background activity within your JS code inside your child activity derived from the DroidGap activity. For example have a background thread in your activity, have a JS callback function and let the thread call this callback functionality.
If you really need a service you have to go native.
Update:
JS code can only be executed with the Droidgap activity. An activity can have 3 states (based on the Lifecycle of activites):
visible
invisible but still loaded
not loaded
I provided a sample in which I implemented a Phonegap plugin. The plugin allows the activity to register itself to SMS_RECEIVED. When the activies goes out of scope (event onbeforeunload), it deregisters, so only issue 1 is handled.
When you want all 3 issues handled, you have to forward the incoming SMS intent to the activity. When it is not loaded the system will automatically load and activate the activity. But this is not a background service anymore, your app would become visible whenever a SMS is received.
If you don't want this (if you really want a background service), you have to provide a native implementation.
There is this article on how to create a service on Android with Phonegap which gives some good information on your problem.
It's using a great plugin in order to build a background service with phonegap easily. But you can't use JS though
I didn't find a way to make JS to run in the Background. BUT you can pass parameters from Java to JS and vice versa with the plugin...which is pretty useful.
You would still need to rewrite your JS code in Java though.
Unless you do have a specific reason to only want JS to be run? (But there shouldn't be...)
Hope that could be useful to some people visiting this page.
YES, and it is very simple... just install the plugin backgroundJS:
https://build.phonegap.com/plugins/430
It allows you to run javascript on the background and combined with the local notification plugin, you can even send notifications to the user at any time, just keep in mind that doing this will cause the battery to run out faster, also consider that this might create a problem with the iOS policy. good luck!!!
You can try to add plugin cordova-plugin-background-mode
But as author says:
Infinite background tasks are not official supported on most mobile operation systems and thus not compliant with public store vendors. A successful submssion isn't garanteed.
Use the plugin by your own risk!

System Notification not running in background

I have developed a Web application using Phonegap which reads cross domain Rss feeds using Google-Feed API and sends system notification to the user if a new feed is available.
I have used this Phonegap System Notification Plugin for creating push notifications.
This is the SystemNotificaton.java that comes with the plugin.
This is the SystemNotification.js file that comes with the plugin, which has all the methods that can be used in your javascript file.
This is my notification.js javascript file were I have created two functions to read two separate Rss feed urls and I have used setIntervals to call the function every 1 min.I have also called navigator.systemNotification.onBackground(); method inside the same function so that when my app is not active this function keeps running in the background and displays the notification to the user if a new feed comes up.
The problem is I get notifications once the application starts then when i close the application I get a couple of more, after one or two days the notification stops coming. I know since I am using google-feed api it is not real time but still even after two days it does not work . It seems like the onbackground method it not working. Could anyone point out what mistake I am doing.
I don't know much about Phonegap, but I know a fair bit about Android development, and it sounds to me like the notifications aren't your problem. (Incidentally, these are just notifications, not "Push" notifications. Those are another beast altogether.)
I suspect that your application is simply stopping, and you don't have anything set to start it back up. The Android OS will kill any background application for a variety of reasons. If implemented as a service, the OS is supposed to restart it at some point, but that's not entirely reliable.
Basically, you need to set an alarm to babysit your service and make sure it stays alive. If this is possible in PhoneGap, I recommend getting rid of the setInterval altogether, and just using the alarm to wake your app up and trigger the RSS polling action. The benefit of this is that it will still work when the device goes to sleep.
Doing a bit of quick searching seems to indicate that PhoneGap does not have access to the AlarmManager. It could be done with a plugin, maybe, but PhoneGap doesn't strike me as a good framework for background services in general. A truly native app is going to be far better behaved in this context.

Categories

Resources