1.效果图:js调用java 代码
2.类
public class MainActivity extends AppCompatActivity {
private WebView contentWebView = null;
private TextView msgView = null;
@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentWebView = (WebView) findViewById(R.id.native_wv);
msgView = (TextView) findViewById(R.id.msg);
WebSettings webSettings = contentWebView.getSettings();
webSettings.setJavaScriptEnabled(true); // 启用JavaScript
//允许弹出框
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
contentWebView.loadUrl("file:///android_asset/js.html");
// 原生方式,注册交互的类
contentWebView.addJavascriptInterface(new JsToJava(), "stub");
}
private class JsToJava{
@JavascriptInterface
public void jsMethod(final String paramFromJS){
runOnUiThread(new Runnable() {
@Override
public void run() {
msgView.setText("传统方式js调用java,参数:" + paramFromJS);
}
});
}
}
}
3.html
<html>
<head>
<title>JS交互</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function promptTest(param){
prompt(param);
}
</script>
</head>
<body>
<p id="content"></p>
<p>
<input type="button" value="调用Java方法" onclick="window.stub.jsMethod('哈士奇参数测试');" /><br />
<hr />
<input type="button" value="prompt方式" onclick="promptTest('prompt方式的参数')" /><br />
<hr />
<a href="http://www.baidu.com" target="_blank" rel="external nofollow" >链接方式</a>
</p>
</body>
</html>