在Android中的服务中运行JavaScript

Por*_*nny 8 javascript android rhino android-service android-webview

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

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

AFAIK有2种选择?

  • V8内置于标准的WebView和超高速,没有额外的apk膨胀.
  • 犀牛,开始使用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.
Run Code Online (Sandbox Code Playgroud)

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

我的问题分为三部分;

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

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

3)如果上述任何一种情况都是不可能的......我想我会去得到Rhino,任何提示都会受到赞赏,我只看到一些博客抱怨有关在Android上运行的问题,并想知道是否有一个"转到"版本的android维护在某处.

Por*_*nny 6

从服务的内心深处找不到关于V8的任何信息.

结束使用Rhino,但是对任何跟随我的脚步的人发出警告,这是非常缓慢的.

只需从https://developer.mozilla.org/en-US/docs/Rhino/Download_Rhino?redirectlocale=en-US&redirectslug=RhinoDownload中获取Rhino官方最新发布的jar即可.

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());
Run Code Online (Sandbox Code Playgroud)

  • 我和你一样有类似的html解析情况!我现在不是在努力,但是当我这样做时,我可能会在这里分享我的结果.谢谢 (2认同)