在Android中的服务中运行JavaScript

时间:2013-05-08 13:31:58

标签: javascript android android-webview android-service rhino

我的业务逻辑是用JavaScript编写的,这段代码与其他非Android应用程序共享。

在Android中的服务中使用此JavaScript中的函数的最佳方法是什么。

AFAIK,有两种选择?

  • 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后我什么也得不到。

我的问题分为3部分;

1)有没有人在没有UI线程的情况下在webview中运行javascript有什么成功?

2)如何从javascript中的函数获得结果,webview界面“addJavascriptInterface”是否支持加载参数并将其发送回java?

3)如果上述任何一种情况都是不可能的......我想我会去获取Rhino,任何提示都会受到赞赏,我只看到一些博客抱怨关于让它进入Android并且想知道的问题如果有一个“转到”版本的android维护在某处。

1 个答案:

答案 0 :(得分:6)

无法在服务的深层找到任何关于V8的内容。

结束使用Rhino,但是对任何跟随我的脚步的人发出警告,它的速度非常慢。

从官方最新发布的Rhino手中抢到罐子 https://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)。使用parse.js脚本,我来自assets文件夹。

Rhino没有附带DOM,并且env.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());