How to run cordova plugin in Android background service?

后端 未结 3 858
礼貌的吻别
礼貌的吻别 2020-12-02 09:38

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

3条回答
  •  天命终不由人
    2020-12-02 10:10

    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.

提交回复
热议问题