一些应用为了节省开发时间,会开用Android、iOS内嵌HTML方式进行开发,在涉及到打电话、发短信这些Android原生功能时,需要涉及到webView中js与ANdroid的交互。这里结合我做过的项目,以其中的拨打电话的功能为例,总结下过程:
1、添加权限声明
<uses-permission android:name="android.permission.CALL_PHONE" />
2、添加JavaScript支持
contentWebView.getSettings().setJavaScriptEnabled(true);
3、重写shouldOverrideUrlLoading(WebView view, String url)方法,对符合和不符合条件的URL进行判断
public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(intent);
return false;
} else {
view.loadUrl(url); return true;
}
}4、在web页面的链接改造成调用js函数,在函数里面执行类似window.js交互接口名.js函数名()。
function func(tel){
window.jsInterface.exitSys(tel);
}5、在Android壳源码里面对应加上js接口声明,比如我的名称是jsInterface。
contentWebView.addJavascriptInterface(new JavascriptInterface(this), "jsInterface");
6、在JavascriptInterface类里面声明与js对应的方法。
public void exitSys(String number) {
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+number));
startActivity(intent);
}7、被调用的js如有需要请动态传参。
8、在web页面加上浏览器判断操作系统类型,并执行对应的js函数。
$(document).ready(function(){
$("a").each(function(){ var u = navigator.userAgent; if(u.indexOf('iPhone') > -1){
} else { if($(this).attr("href").length>4&&$(this).attr("href").indexOf("tel:")==0){
$(this).attr("href","javascript:exitSys('"+$(this).attr("href").replace("tel:","")+"')");
}
}
});
});
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦