android与js之间的交互

简单介绍Webview的使用

记得添加权限:

方法1:加载网络地址

webView.loadUrl("https://www.baidu.com");

方法2:加载本地网页

写一段简单的html代码:


Hello World

将网页放在assets文件夹中

webView.loadUrl("file:///android_asset/test1.html");

方法3:加载html代码

String html = " 

Hello World from code

"; webView.loadData(html , "text/html", "utf-8");

先贴出html代码,保存为html文件放到assets文件夹中:









等待android端传来信息


首先添加webview的相关设置:

//       开启对js的支持
        webView.getSettings().setJavaScriptEnabled(true);

JS调用android方法:

        jsHook = new JsHook();
//        添加js接口
        webView.addJavascriptInterface(jsHook , "test");

JsHook类如下:

    class JsHook{
        @JavascriptInterface
        public void androidMethod(String info){
            Toast.makeText(MainActivity.this , info, Toast.LENGTH_SHORT).show();
        }
    }

@JavascriptInterface 从字面上看就是js接口,说明加了此标签的方法可以被js调用

android调用js方法:

    public void click(View view){
        String info = "I am from android";
        webView.loadUrl("javascript:show('"+info+"')");
    }

注意:

1.android调用js方法必须要与创建webview在同一线程中,否则会报java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'Thread-6'. All WebView methods must be called on the same thread.

2.添加了@JavascriptInterface标签的方法,并不是在主线程中运行的,我打印出来的ThreadNamge:Threadname =>JavaBridge

你可能感兴趣的:(Android)