欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android中javascript和java互相调用

程序员文章站 2024-01-06 21:55:22
...
http://www.jb51.net/article/59951.htm

mWebview = (WebView) findViewById(R.id.web_view);
		mWebview.getSettings().setJavaScriptEnabled(true);
		mWebview.getSettings().setDefaultTextEncodingName("UTF-8");	
		mWebview.setWebChromeClient(new WebChromeClient() {});
		mWebview.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);

				String json = "[{\"name\":\"zxx\", \"amount\":\"9999999\", \"phone\":\"18600012345\"}]";
	            mWebview.loadUrl("javascript:show('" + json + "')");
			}
		}); 
		mWebview.addJavascriptInterface(new WebActor(ActivitiesActivity.this), "contact");
		
		mWebview.loadUrl("file:///android_asset/index.html");


public class WebActor {
	private Activity context;
	public WebActor(Activity context) {
		this.context = context;
	}
	
	@JavascriptInterface
    public void call(String phone) {
//        startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)));
		context.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				PromptManager.showToast(context, "拨打电话1212");
			}
		}); 
    } 
}


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            function show(jsondata){            
                    var jsonobjs = eval(jsondata);
                    var table = document.getElementById("personTable");
                    for(var y=0; y<jsonobjs.length; y++){
                        var tr = table.insertRow(table.rows.length); 
                        var td1 = tr.insertCell(0);
                        var td2 = tr.insertCell(1);
                        td2.align = "center";
                        var td3 = tr.insertCell(2);
                        td3.align = "center";
                        td1.innerHTML = jsonobjs[y].name; 
                        td2.innerHTML = jsonobjs[y].amount; 
                        td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>"; 
                    }
            }
        </script>
    </head>
    <body onload="javascript:contact.showcontacts()">
       <table border="0" width="100%" id="personTable" cellspacing="0">
            <tr>
                <td width="30%">姓名</td>
                <td width="30%" align="center">存款</td>
                <td align="center">电话</td>
            </tr>
        </table>
    </body>
</html>

上一篇:

下一篇: