Android与JS之间的互调

本例以加载本地Html文件来写Demo

WebView加载本地html文件,可以将Html文件放在:assets文件中

myWebView.loadUrl("file:///android_asset/XX.html");  
Android与JS交互,必须对WebView进行一下设置

WevSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnable(true);

Android与JS的交互,需要创建一个桥接对象,通过桥接对象来实现交互

public class JSHook {
        @JavascriptInterface
        public void javaMethod(String p) {
            if (!TextUtils.isEmpty(p)) {
                text.setText(p);
            }
        }

        @JavascriptInterface
        public void showAndroid() {
            final String phone = Build.MODEL;
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:show('" + phone + "')");
                }
            });
        }
    }

WebView通过addJavascriptInterface方法将js与Android通过桥接对象进行连接

webView.addJavascriptInterface(new JSHook(), "demo");


下面是整体代码

Html代码:




    
    Js与Android互调Demo
    



测试






MainActivity代码

public class MainActivity extends AppCompatActivity {
    private static final String URL = "file:///android_asset/html.html";
    private WebView webView;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.text);
        webView = (WebView) findViewById(R.id.webview);
        webView.loadUrl(URL);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JSHook(), "demo");
    }

    public class JSHook {
        @JavascriptInterface
        public void javaMethod(String p) {
            if (!TextUtils.isEmpty(p)) {
                text.setText(p);
            }
        }

        @JavascriptInterface
        public void showAndroid() {
            final String phone = Build.MODEL;
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:show('" + phone + "')");
                }
            });
        }
    }
}

布局文件xml代码



   
   




Android与JS之间的互调_第1张图片





你可能感兴趣的:(安卓开发)