我们知道,大前端时代已经来了!不管是网页web,还是移动端,通过前端的知识基本都可以解决需求问题。作为一名靠Android平台吃饭的程序员,的确有了些许压力。不过也不用太紧张,个人观点觉得最近几年都是ok的,问题不大。目前市场上流行的做法是,在app的基础上,与HTML相结合,实现嵌套交互的效果。因为,大部分应用,都是需要通过用户来实现收益的,因此经常会推出活动来推广运营。这样的情况下,如果每次都更新应用版本来实现的话,都要经过打包,发版,渠道上线等流程,会显得麻烦,也不符合快速迭代的思维。这样,嵌套Html的方式就出现了,完美!
所以,通过这篇文章,将阐述Android平台通过WebView与JS交互的基础知识。Android与JS的交互式相互的中间桥梁就是WebView。
1、Android调用JS
Android调用JS的方法有两种,
- 通过WebView的loadUrl()
- 通过WebView的evaluateJavascript()
通过WebView的loadUrl
1.将需要调用的JS代码以.html格式放到src/main/assets文件夹里
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson_Ho</title>
// JS代码
<script>
// Android需要调用的方法
function callJS(){
alert("Android调用了JS的callJS方法");
}
</script>
</head>
</html>
- 在Android里通过WebView设置调用JS代码
mWebView = (WebView) findViewById(R.id.webview);
mButton = (Button) findViewById(R.id.button);
WebSettings webSettings = mWebView.getSettings();
//支持javascript
webSettings.setJavaScriptEnabled(true);
//允许弹窗
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.loadUrl("file:///android_asset/JsTest.html");
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 通过Handler发送消息
mWebView.post(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void run() {
// 注意调用的JS方法名要对应上
// 调用javascript的callJS()方法
mWebView.loadUrl("javascript:callJS()");
});
}
});
// 由于设置了弹窗检验调用结果,所以需要支持js对话框
// webview只是载体,内容的渲染需要使用webviewChromClient类去实现
// 通过设置WebChromeClient对象处理JavaScript的对话框
//设置响应js 的Alert()函数
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
b.setTitle("Alert");
b.setMessage(message);
b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
b.setCancelable(false);
b.create().show();
return true;