android javaScript数据传递

文中代码来自网上,在此引用只做分析

    android中加载html文件时使用的是WebView控件,如果是加载网络中的html文件,就要在AndroidManifest.xml文件中添加访问网络的权限:android.permission.INTERNET。加载本地assets目录下的html文件就不用加了。本文的代码实例中就是加载的assets中的index.html文 件。

    在本实例的index.html中使用了javaScript,所以webview必须支持Javascript。

	webView.getSettings().setJavaScriptEnabled(true);
    MainActivity代码

package com.chinasofti.html;

import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.chinasofti.domain.Contact;
import com.chinasofti.service.ContactService;
import com.example.jstest.R;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private ContactService contactService;
    private WebView webView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactService = new ContactService();
        webView = (WebView) this.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new ContactPlugin(), "contact");
        webView.loadUrl("file:///android_asset/index.html");
    }

    private final class ContactPlugin {
        public void getContacts() {
            List<Contact> contacts = contactService.getContacts();
            try {
                JSONArray array = new JSONArray();
                for (Contact contact : contacts) {

                    JSONObject item = new JSONObject();
                    item.put("id", contact.getId());
                    item.put("name", contact.getName());
                    item.put("mobile", contact.getMobile());
                    array.put(item);
                }
                String json = array.toString();
                Log.i(TAG, json);
                webView.loadUrl("javascript:show('" + json + "')");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        public void call(String mobile) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
            startActivity(intent);
        }

        public void startAcivity() {
            Intent intent = new Intent(MainActivity.this, NewActivity.class);
            startActivity(intent);
        }
    }
}



    在MainActivity的onCreate方法代码:

	webView = (WebView) this.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);//使webview支持javascript 
	webView.addJavascriptInterface(new ContactPlugin(), "contact");//加载ContactPlugin对象 取昵称contact 在JavaScript中使用       
	 webView.loadUrl("file:///android_asset/index.html");//加载assets目录下的index.html文件

至此完成了index.html的加载,下面我们来看一下index.html文件。

<!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].id; 
                        td2.innerHTML = jsonobjs[y].name; 
                        td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].mobile+ "\")'>"+ jsonobjs[y].mobile+ "</a>"; 
                        }
        }
</script>

</head>
<!-- js代码通过webView调用其插件中的java代码 -->
<body οnlοad="javascript:contact.getContacts()">
   <table border="0" width="100%" id="personTable" cellspacing="0">
                <tr  bgcolor="#00FFCC">
                        <td width="20%">编号</td><td width="40%" align="center">姓名</td><td align="center">电话</td>
                </tr>
        </table>
        <img src="images/ic_launcher.png" >
        <a href="javascript:window.location.reload()">刷新</a>
        <a href="javascript:contact.startAcivity()">跳转</a>

</body>
</html>

οnlοad="javascript:contact.getContacts()"
在页面被加载后执行ContactPlugin  contact的getContacts()方法。
public void getContacts() {
            List<Contact> contacts = contactService.getContacts();
            try {
                JSONArray array = new JSONArray();
                for (Contact contact : contacts) {

                    JSONObject item = new JSONObject();
                    item.put("id", contact.getId());
                    item.put("name", contact.getName());
                    item.put("mobile", contact.getMobile());
                    array.put(item);
                }
                String json = array.toString();
                Log.i(TAG, json);
                webView.loadUrl("javascript:show('" + json + "')");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

在执行到webView.loadUrl("javascript:show('" + json + "')");将生成的JSON字符串传递到index.html中javaScript的show()方法中

<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].id; 
                        td2.innerHTML = jsonobjs[y].name; 
                        td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].mobile+ "\")'>"+ jsonobjs[y].mobile+ "</a>"; 
                        }
        }
</script>

在show方法中将传递来的字符串解析后逐行显示,并且在每一行的第三列添加了一个链接,
  td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].mobile+ "\")'>"+ jsonobjs[y].mobile+ "</a>";
我们看到在该链接被点击的时候掉用了ContactPlugin  contact的call(String str)方法,同时传递了参数jsonobjs[y].mobile。

 public void call(String mobile) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
            startActivity(intent);
        }

这里call()实现了打电话的功能,此时我们要在AndroidMainfest.xml文件中添加打电话的权限<uses-permission android:name="android.permission.CALL_PHONE"/>下面是在index.html的跳转(打开另外一个activity)

<a href="javascript:contact.startAcivity()">跳转</a>

我们看到这个链接是调用了ContactOlugin contact中的startActivity()方法

public void startAcivity() {
            Intent intent = new Intent(MainActivity.this, NewActivity.class);
            startActivity(intent);
        }

该方法就是打开NewActivity。

在这个实例中

activity向Javascript传递数据使用 webView.loadUrl("javascript:show('" + json + "')");

javascript向activity传递数据使用'javascript:contact.call(\""+ jsonobjs[y].mobile+ "\")'   方法调用"javascript:contact.startAcivity()"、"javascript:contact.getContacts()"。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值