3分钟入门 Java Js 相互调用

初始化WebView。

        mWebView = root.findViewById(R.id.web_view);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new JsBridge(), "javaObjectA");

JsBridge.java
被JavaScript调用的方法要加上@JavascriptInterface

    public class JsBridge {
        @JavascriptInterface
        public void javaMethod(int value) {
            System.out.println("java method: " + value);
        }
    }

Java调用JavaScript

Java代码

    mWebView.loadUrl("javascript:window.javaObjectA.javaMethod(100);");

JavaScript调用Java

JavaScript代码

    window.javaObjectA.javaMethod(100);

WebView方法说明

WebView.addJavascriptInterface解释

    /**
     * Injects the supplied Java object into this WebView. The object is
     * injected into the JavaScript context of the main frame, using the
     * supplied name. This allows the Java object's methods to be
     * accessed from JavaScript.
     * @param object the Java object to inject into this WebView's JavaScript
     *               context. Null values are ignored.
     * @param name the name used to expose the object in JavaScript
     */
    public void addJavascriptInterface(Object object, String name) {
        checkThread();
        mProvider.addJavascriptInterface(object, name);
    }

addJavascriptInterface(Object object, String name)
第一个参数是被注入到WebView中的java对象,JavaScript可以操作该对象有@JavascriptInterfacepublic方法。
第二个参数是java 类暴露给JavaScript的名字。mWebView.addJavascriptInterface(new JsBridge(), "javaObjectA");将new 出来的JsBridge对象注入到了WebView中,并命名为了JavaObjectA。JavaScript可以通过window.javaObjectA.javaMethod(100);调用该java对象的javaMethod()方法。

你可能感兴趣的:(3分钟入门 Java Js 相互调用)