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 wi
WebViews can not execute javascript from a background service.
I would recommend using native code instead. But if you must use javascript, i would try this library
https://code.google.com/p/jav8/
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("jav8");
try {
engine.eval("print('Hello, world!')");
} catch (ScriptException ex) {
ex.printStackTrace();
}
First load the contens of your script into a string and then run engine.eval() method.
Example (Run "test.js" from assets):
AssetManager am = context.getAssets();
InputStream is = am.open("test.js");
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("jav8");
try {
engine.eval(total.toString());
} catch (ScriptException ex) {
ex.printStackTrace();
}
Notice!
The eval function expects only a javascript function to be executed at a time and returns the value of this function.