简体   繁体   English

如何在Android后台服务中运行cordova插件?

[英]How to run cordova plugin in Android background service?

I am working on mobile application developed on cordova . 我正在研究在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. 关键是我在javascript中实现了这个代码,但我想在后台执行它。

I searched internet for a cordova background service plugin. 我在互联网上搜索了一个cordova后台服务插件。

I have read some topics about background service in android these are useful ones I found: 我已经阅读了一些关于android中后台服务的主题,这些是我发现的有用的:

So I started writing cordova plugin (primarily on android) to execute the javascript code in background. 所以我开始编写cordova插件(主要是在android上)来在后台执行javascript代码。 I created a webview from the background service to execute the javascript from it. 我从后台服务创建了一个webview来执行它的javascript。 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 . 这在我执行普通javascript时工作正常,但是当涉及到cordova插件时,它失败,例如设备device.uuid给出null

This is the java service code: 这是java服务代码:

      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. 更新 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 
   }

I tried to replace the standard webView with cordovaWebView But the same result is given. 我试图用cordovaWebView替换标准的webView但是给出了相同的结果。

       //WebView wv = new WebView(this);  Commented out
       CordovaWebView wv = new CordovaWebView(this);

Any help about this problem ? 有关此问题的任何帮助?

You should use an embedded Cordova WebView, not a standard WebView. 您应该使用嵌入式Cordova WebView,而不是标准WebView。 A standard WebView is not set up to handle Cordova plugins, and the device info is a plugin. 标准WebView未设置为处理Cordova插件,设备信息是插件。

See the Cordova docs on embedding webviews . 有关嵌入webview的信息,请参阅Cordova文档

WebViews can not execute javascript from a background service. WebViews无法从后台服务执行javascript。

I would recommend using native code instead. 我建议使用本机代码。 But if you must use javascript, i would try this library 但如果你必须使用javascript,我会尝试这个库

https://code.google.com/p/jav8/ 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. 首先将脚本的匹配加载到字符串中,然后运行engine.eval()方法。

Example (Run "test.js" from assets): 示例(从资产运行“test.js”):

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. eval函数只需要一次执行javascript函数并返回此函数的值。

To work with Cordova plugins in WebView as background service, i've created class that implements CordovaInterface. 为了在WebView中使用Cordova插件作为后台服务,我创建了实现CordovaInterface的类。 Here is an example 这是一个例子

 private class CordovaBackground extends Activity implements CordovaInterface {
    private ArrayList pluginEntries = new ArrayList();
    private CordovaPreferences preferences;
    private Context context;
    private Whitelist internalWhitelist;
    private Whitelist externalWhitelist;
    private CordovaWebViewBackground webView;
    protected LinearLayout root;
    private WindowManager serviceWindowManager;
    private final ExecutorService threadPool = Executors.newCachedThreadPool();

    public CordovaBackground(Context context, WindowManager windowManager) {
        attachBaseContext(context);
        this.context = context;
        this.serviceWindowManager = windowManager;
    }

    private void loadConfig() {
        ConfigXmlParser parser = new ConfigXmlParser();
        parser.parse(this);
        preferences = parser.getPreferences();
        internalWhitelist = parser.getInternalWhitelist();
        externalWhitelist = parser.getExternalWhitelist();;
        ArrayList<PluginEntry> allPluginEntries = parser.getPluginEntries();
        String[] backgroundPluginNames = {"File"};//not all plugins you need in service, here is the list of them
        ArrayList<String> backgroundPlugins = new ArrayList<String>(
            Arrays.asList(backgroundPluginNames));
        for (PluginEntry pluginEntry : allPluginEntries) {
            if (backgroundPlugins.contains(pluginEntry.service)) {
                pluginEntries.add(pluginEntry);
            }
        }
    }

    public void loadUrl(String url) {
        init();
        webView.loadUrl(url);
    }

    public void init() {
        loadConfig();
        webView = new CordovaWebViewBackground(context);
        if (webView.pluginManager == null) {
            CordovaWebViewClient webClient = webView.makeWebViewClient(this);
            CordovaChromeClientBackground webChromeClient = webView.makeWebChromeClient(this);
            webView.init(this, webClient, webChromeClient,
                    pluginEntries, internalWhitelist, externalWhitelist, preferences);
        }
    }

    public WindowManager getWindowManager() {
        return serviceWindowManager;
    }

    @Override
    public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
    }

    @Override
    public void setActivityResultCallback(CordovaPlugin plugin) {
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public Object onMessage(String id, Object data) {
        return null;
    }

    @Override
    public ExecutorService getThreadPool() {
        return threadPool;
    }

    @Override
    public Intent registerReceiver(android.content.BroadcastReceiver receiver, android.content.IntentFilter filter) {
        return  getIntent();
    }

    @Override
    public String getPackageName() {
        return context.getPackageName();
    }

}

To prevent errors while cordova initializing, i've overrode onJsAlert method. 为了防止在cordova初始化时出错,我已经过了onAsAlert方法。 If you have a time, you may have found better way. 如果你有时间,你可能找到了更好的方法。

 private class CordovaWebViewBackground extends CordovaWebView {

    public CordovaWebViewBackground(Context context) {
        super(context);
    }

    public CordovaChromeClientBackground makeWebChromeClient(CordovaInterface cordova) {
        return new CordovaChromeClientBackground(cordova, this);
    }

}

private class CordovaChromeClientBackground extends CordovaChromeClient {

    public CordovaChromeClientBackground(CordovaInterface ctx, CordovaWebView app) {
        super(ctx, app);
    }

    public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
        //super.onJsAlert(view, url, message, result);
        return true;
    }

}

How to use: 如何使用:

WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
CordovaBackground cordovaBackground = new CordovaBackground(this, wm);
cordovaBackground.setIntent(intent);
String url = "file:///android_asset/www/test.html";
cordovaBackground.loadUrl(url);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM