手记

Android开发webview与js的交互总结【安卓巴士博文大赛】

一些应用为了节省开发时间,会开用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:","")+"')");
                }
            }
        });
    });

附 参赛地址:
http://www.apkbus.com/thread-282214-1-1.html

原文链接:http://www.apkbus.com/blog-329789-68710.html

0人推荐
随时随地看视频
慕课网APP