本例以加载本地Html文件来写Demo
WebView加载本地html文件,可以将Html文件放在:assets文件中
myWebView.loadUrl("file:///android_asset/XX.html");
Android与JS交互,必须对WebView进行一下设置
WevSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnable(true);
Android与JS的交互,需要创建一个桥接对象,通过桥接对象来实现交互
public class JSHook {
@JavascriptInterface
public void javaMethod(String p) {
if (!TextUtils.isEmpty(p)) {
text.setText(p);
}
}
@JavascriptInterface
public void showAndroid() {
final String phone = Build.MODEL;
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:show('" + phone + "')");
}
});
}
}
WebView通过addJavascriptInterface方法将js与Android通过桥接对象进行连接
webView.addJavascriptInterface(new JSHook(), "demo");
下面是整体代码
Html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Js与Android互调Demo</title>
<script type="text/javascript">
function show(info){
document.getElementById("shows").innerHTML = info;
}
</script>
</head>
<body>
<b>测试</b>
<br/>
<button onClick="window.demo.javaMethod('JS中的数据')">将数据传个原生控件</button>
<br/>
<hr color="#99FF00"/>
<button onClick="window.demo.showAndroid()">点击我获取手机型号</button>
<br/>
<textarea id="shows" cols="20" rows="10"> 默认的内容 </textarea>
<br/>
</body>
</html>
public class MainActivity extends AppCompatActivity {
private static final String URL = "file:///android_asset/html.html";
private WebView webView;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl(URL);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSHook(), "demo");
}
public class JSHook {
@JavascriptInterface
public void javaMethod(String p) {
if (!TextUtils.isEmpty(p)) {
text.setText(p);
}
}
@JavascriptInterface
public void showAndroid() {
final String phone = Build.MODEL;
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:show('" + phone + "')");
}
});
}
}
}
布局文件xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.kevin.myapplication.MainActivity">
<TextView
android:id="@+id/text"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="20dp" />
<WebView
android:id="@+id/webview"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"></WebView>
</LinearLayout>