如何实现?
Demo链接
https://github.com/SuperTenger/JsinteractionDemo
1.Android调用JS方法
webView.loadUrl("javascript:jsfunction()");
2.JS调用Android方法
Android中的一些设置
webView.getSettings().setJavaScriptEnabled(true);//首先要设置webview支持JavaScript脚本
//添加JavascriptInterface
webView.addJavascriptInterface(new JsInteration(), "control");
private class JsInteration {
@JavascriptInterface
public String javaFunc(String msg) {
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
return "javaFunc ok";
}
}
JS调用
window.control.javaFunc("JS调用JAVA方法")
可以看出调用起来非常方便,并且如果JS调用java方法,想获取返回值的话也可以直接获取
var str = window.control.javaFunc("JS调用JAVA方法")
Android调用JS方法想获取返回值,只需再写一个带参数的java方法供js调用,调用时将返回值传入,
java代码中便能获取返回值了
@JavascriptInterface
public void responseMsg(String responseMsg) {
this.responseMsg = responseMsg;
}
window.control.responseMsg("JS返回值")
话不多说,直接上代码
MainActivity.java
public class MainActivity extends Activity {
WebView webView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JsInteration(), "control");
webView.loadUrl("file:///android_asset/demo.html");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("javascript:jsfunction()");
}
});
}
private class JsInteration {
String responseMsg;
@JavascriptInterface
public String javaFunc(String msg) {
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
return "javaFunc ok";
}
@JavascriptInterface
public void responseMsg(String responseMsg) {
Toast.makeText(getApplicationContext(),responseMsg,Toast.LENGTH_SHORT).show();
this.responseMsg = responseMsg;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:text="java调用js方法"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</LinearLayout>
demo.html
<html>
<body>
<p>
<xmp id="show">
</xmp>
</p>
<p>
<input type="button" id="enter1" value="JS调用JAVA方法" onclick="testClick();"/>
</p>
</body>
<script>
function testClick() {
var str = window.control.javaFunc("JS调用JAVA方法")
document.getElementById("show").innerHTML = str
}
function jsfunction(){
document.getElementById("show").innerHTML = "调用JS方法成功"
window.control.responseMsg("JS返回值")
}
</script>
</html>