1. Basic usage of WebView
1. Usage of loading html page through webView:
//例如:加载assets文件夹下的test.html页面
mWebView.loadUrl("file:///android_asset/test.html")
//例如:加载网页
mWebView.loadUrl("http://www.baidu.com")
//例如:加载assets文件夹下的test.html页面
mWebView.loadUrl("file:///android_asset/test.html")
//例如:加载网页
mWebView.loadUrl("http://www.baidu.com")
Note: Generally, the webpage will be opened inside the App, otherwise, it will be opened on the default browser of your phone. At the same time, make the App title display the title of the H5 page. Set up WebViewClient:
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {//设置App内部打开网页
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {//设置标题
tv_title.setText(view.getTitle());
}
});
2. WebVIew Access HTTPS (protocol request using ssl encrypted url time ). If it is not processed, the page is blank. When opened with the browser that comes with the system, a dialog box for confirming the certificate will pop up. The processing required is to rewrite the onReceivedSslError method of the WebViewClient class , as follows: @Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
Two, WebView and H5 interaction
Prerequisite: Calling the js method must be supported by webView
WebSettings webSettings = mWebView.getSettings();
//设置为可调用js方法
webSettings.setJavaScriptEnabled(true);
1 Android calls the JavaScript method in the HTML page locally
WebSettings webSettings = mWebView.getSettings();
//设置为可调用js方法
webSettings.setJavaScriptEnabled(true);
//若调用的js方法没有返回值 do()方法为JS的方法
mWebView.loadUrl("javascript:do()");
//有返回值
mWebView.evaluateJavascript("do(1,2)", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Log.e(TAG, "onReceiveValue value=" + value);
}
});
2. js calls Android native Java methods
//若调用的js方法没有返回值 do()方法为JS的方法
mWebView.loadUrl("javascript:do()");
//有返回值
mWebView.evaluateJavascript("do(1,2)", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Log.e(TAG, "onReceiveValue value=" + value);
}
});
First, define a Java class:
public class JsInteration {
@JavascriptInterface //Android4.2以上可以直接使用@JavascriptInterface注解来声明
public String back() {
return "hello world";
}
}
Then, call the method in Android in js
public class JsInteration {
@JavascriptInterface //Android4.2以上可以直接使用@JavascriptInterface注解来声明
public String back() {
return "hello world";
}
}
//第一个参数是 供给js调用的类,第二个参数是js中要用到的调用这个类中的方法的对象,可以随便起
mWebView.addJavascriptInterface(new JsInteration(), "android");
Question: Sometimes it is encountered that Js calls the android method invalid. Solution:
//第一个参数是 供给js调用的类,第二个参数是js中要用到的调用这个类中的方法的对象,可以随便起
mWebView.addJavascriptInterface(new JsInteration(), "android");