Android 与JS交互总结(包括J2V8)

2020-09-21  本文已影响0人  RookieRun

Android与JavaScript相互调用

Java调用JS

通过WebView

         webView.evaluateJavascript("" +
                "var hello='hello,' ;\n" +
                "var world = 'world!';\n" +
                "hello.concat(world).length;\n", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Log.e("test", "ValueCallback--->" + value);
            }
        });
- 加载html中的js方法

         mWebView.loadUrl("javascript:callJS()");
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("javascript:callJS()", null);
        }

通过J2V8

      public void executeIntegerScript(View view) {
        V8 runtime = V8.createV8Runtime();
        final int result = runtime.executeIntegerScript("" +
                "var hello='hello,' ;\n" +
                "var world = 'world!';\n" +
                "hello.concat(world).length;\n");
        System.out.println(result);
        runtime.release();

    }
      /**
     * 通过方法名执行JS代码
     *
     * @param view
     */
    public void executeScriptWithMethodName(View view) {
        final String fileContent = AssetsUtil.getAssetsFileContent("test.js", this);
        v8.executeScript(fileContent);
        final V8Array arrayArgs = new V8Array(v8).push(12).push(21);
        final int result = v8.executeIntegerFunction("add", arrayArgs);
        arrayArgs.release();
        System.out.println("result of executeScriptWithMethodName--->" + result);
    }
       /**
     * 通过Function对象执行JS代码
     *
     * @param view
     */
    public void executeScriptWithFunctionObj(View view) {
        final String fileContent = AssetsUtil.getAssetsFileContent("test.js", this);
        if (v8.getType("add") == V8.V8_FUNCTION) {
            final V8Array args = new V8Array(v8).push(12).push(23);
            final V8Function addFunction = (V8Function) v8.getObject("add");
            final Object result = addFunction.call(null, args);
            System.out.println("result of executeScriptWithFunctionObj--->" + result);
            args.release();
            addFunction.release();
        }
    }

JS调用Java

通过WebView

 html:<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Android调用 JS 代码demo</title>
<body>
    <button type="button" id="button1" onclick="callAndroid()"></button>
</body>

<script>
       // Android需要调用的方法
       function callJS(){
          alert("Android调用了JS的callJS方法");
       }
       function callAndroid(){
          androidToJs.hello("Js调用了Java的hello方法");
       }


</script>
</head>
</html>
class AndroidToJS {
    @JavascriptInterface
    public void hello(String msg) {
        Log.e("test", "js call Java Method to say :" + msg);
    }
}
 webView.addJavascriptInterface(new AndroidToJS(), "androidToJs");

通过J2V8

JavaCallback/JavaVoidCallback

 JavaVoidCallback voidCallback = new JavaVoidCallback() {
            @Override
            public void invoke(V8Object v8Object, V8Array parameters) {
                if (parameters != null && parameters.length() != 0) {
                    final Object o = parameters.get(0);
                    System.out.println("testJ2V8WithJavaCallBack---argument-->" + o);
                    if (o instanceof Releasable) {
                        ((Releasable) o).release();
                    }
                }
            }
        };
        //指定JS调用print方法时,回调callback中的invoke方法
        v8.registerJavaMethod(voidCallback, "print");
        //以下代码,控制台将打印出:testJ2V8WithJavaCallBack---argument-->hello,world,123
        v8.executeScript("print('hello,world,123')");
Registering Methods Reflectively

class TestConsole {
        public void log(final String message) {
            System.out.println("TestConsole---[INFO] " + message);
        }

        public void error(final String error) {
            System.out.println("TestConsole----[ERROR] " + error);
        }

        public void start() {
            TestConsole testConsole = new TestConsole();
            V8Object v8Console = new V8Object(v8);
            v8.add("testConsole", v8Console);
            //这里可以实现java对象与JS方法的一对一或者一对多的关系,只需Java对象中有对应的方法与之对应即可
//            v8.registerJavaMethod(testConsole, "javaMethod", "jsMethod",new Class[]{String.class});
            v8Console.registerJavaMethod(testConsole, "log", "log", new Class[]{String.class});
            v8Console.registerJavaMethod(testConsole, "error", "error", new Class[]{String.class});
            v8Console.release();
            //以下代码,控制台将打印出: TestConsole---[INFO] hello,world
            v8.executeScript("testConsole.log('hello,world')");
        }
    }
上一篇下一篇

猜你喜欢

热点阅读