First, now assets create a new html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<script type="text/javascript">
function getAllPick(){
document.getElementById("content").innerHTML =
"<br\>JAVA调用了JS的无参函数";
}
function getAllPickWith(arg){
document.getElementById("content").innerHTML =
("<br\>"+arg);
}
</script>
</head>
<body>
HTML 内容显示 <br/>
<h1><div id="content">内容显示</div></h1>
<br/>
<input type="button" value="点击调用java代码" onclick="window.AndroidJs.setImageNull()" />
<br/>
<input type="button" value="点击调用java代码并传递参数" onclick="window.AndroidJs.setImage('http://blog.csdn.net/Leejizhou')" />
</body>
</html>
webview interface code
private WebView webView;
private WebSettings settings;
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl(url);
// webView.loadUrl("file:///android_asset/web.html");
webView.addJavascriptInterface(WebActivity.this, "AndroidJs");
settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
//WebView发起的WEB请求因为网络原因失败时回调
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
//WebView发起的WEB请求收到服务器的错误消息时回调
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//在pagefinish处调用
webView.loadUrl("javascript:getAllPick()");
}
});
@JavascriptInterface
public void setImageNull() {
Log.e("fhxx", "网页获取 -----》这是不穿参数的" );
}
@JavascriptInterface
public void setImage(String str) {
Log.e("fhxx", "网页获取 -----》" + str);
}
After loading the webpage in the native webview, it will pass pageFinish
webView.loadUrl("javascript:getAllPick()");
Automatically call the method in getAllPick() of js
If you want to call the parameter, use
webView.loadUrl("javascript:getAllPick()");
------
Clicking the first button in js will call the native setImageNull() method
The second empathy
After the second self-test is completed, the background can be used according to the name you set
Pay attention to the details, I mark it with different colors, and the same color of android and js should be consistent
webView.addJavascriptInterface(WebActivity.this, "AndroidJs");
To be with js in
window.AndroidJs.setImageNull ( ) keeps always
The method name should be consistent with the calls on both sides
@JavascriptInterface
public void setImageNull () { Log.e("fhxx", "Web page acquisition-----" this does not use parameters" );
}
webView.loadUrl("javascript:getAllPick()");
function getAllPick (){ document.getElementById("content").innerHTML = "<br\>JAVA calls a JS function without parameters"; }