在Android的服务中运行JavaScript

Running JavaScript within a Service in Android

本文关键字:运行 JavaScript 服务 Android      更新时间:2023-09-26

我有一个用JavaScript编写的业务逻辑,该代码与其他非android应用程序共享。

在Android服务中使用这段JavaScript中的函数的最佳方式是什么?

恐怕有两种选择?

  • V8内置到标准的WebView和超快,没有额外的apk膨胀。
  • Rhino,这是棘手的去Android?

专注于V8/Webview,当我试图访问Webview时,使用任何功能,我得到;

All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.

注意到警告,它现在甚至不起作用。当我设置webviewclient时,加载URL后什么也得不到。

我的问题分为三个部分;

1)有没有人在没有UI线程的webview中成功运行javascript ?

2)我如何从javascript内部的函数得到结果,是否webview接口"addJavascriptInterface"支持加载参数并将其发送回java?

如果以上任何一个都是不可能的……我想我会去用Rhino,任何建议都将是感激的,我只看到一些博客抱怨关于在Android上运行Rhino的问题,并想知道是否有一个用于Android的"go to"版本。

在服务中找不到任何关于V8的内容

最后我使用了Rhino,但是我要提醒一下那些跟随我脚步的人,它的速度非常慢。

从Rhino的官方最新发行版中获取jarhttps://developer.mozilla.org/en-US/docs/Rhino/Download_Rhino?redirectlocale=en-US& redirectslug = RhinoDownload

js.jar是你需要的压缩文件。Js-14是一个更大的Java 1.4兼容版本,你不需要。

集成很简单,只要把jar放到你的libs文件夹中。

下面是我使用javascript抓取网页(将数据转换为更好格式的json)。使用我从assets文件夹中创建的parse.js脚本。

Rhino没有附带DOM,并且envy .js会因为stackoverflow错误而崩溃。总的来说,我想说这个解决方案很慢,而且没有得到很好的支持…

public static void sync(Context context, ){
    String url = BASE_URL;
    String html = Utils.inputStreamToString(Utils.getHTTPStream(url));
    timeList.add(System.currentTimeMillis());
    if(html == null){
        Utils.logw("Could not get board list.");
        return;
    }
    String parsingCode = null;
    try {
        parsingCode = Utils.inputStreamToString(context.getAssets().open("parse.js"));
    } catch (IOException e) {
        Utils.logw("Could not get board parser js");
        return;
    }
    // Create an execution environment.
    org.mozilla.javascript.Context cx = org.mozilla.javascript.Context.enter();
    // Turn compilation off.
    cx.setOptimizationLevel(-1);
    try {
        // Initialize a variable scope with bindnings for
        // standard objects (Object, Function, etc.)
        Scriptable scope = cx.initStandardObjects();
        ScriptableObject.putProperty(
                scope, "html", org.mozilla.javascript.Context.javaToJS(html, scope));
        //load up the function
        cx.evaluateString(scope, parsingCode,"parseFunction", 1 , null);
        // Evaluate the script.
        Object result = cx.evaluateString(scope, "myFunction()", "doit:", 1, null);
        JSONArray jsonArray = new JSONArray(result.toString());