简单介绍Webview的使用
记得添加权限:
webView.loadUrl("https://www.baidu.com");
写一段简单的html代码:
Hello World
将网页放在assets文件夹中
webView.loadUrl("file:///android_asset/test1.html");
String html = " Hello World from code
";
webView.loadData(html , "text/html", "utf-8");
等待android端传来信息
// 开启对js的支持
webView.getSettings().setJavaScriptEnabled(true);
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();
}
}
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