android获取联系人信息

android中在webView中显示网页,在网页中通过Js调用通讯录中的联系人信息,显示到webView中。

android获取联系人信息

android获取联系人信息



部分开发代码如下:

首先的Html的代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">

<HTML>
<META http-equiv=Content-Type content="text/html; charset=utf-8"><LINK 
href="css/style_cn.css" type=text/css rel=stylesheet>
<SCRIPT language=JavaScript>

  function contactlist(jsons){  
  var table=document.getElementById("contactTable");//获得html中Table  
  var arr = eval(jsons);//将jsons字符串转换为json对象数组  
  for(var i=0;i < arr.length;i++){  
    var jsonObj = arr[i];  
    var tr = table.insertRow(table.rows.length);//添加tr  
    var td1 = tr.insertCell(0);//td  
    var td2 = tr.insertCell(1);  
    td2.align = "center";  
    var td3 = tr.insertCell(2);  
  
    td1.innerHTML = jsonObj.id;//设置每列对应的值  
    td2.innerHTML = jsonObj.name;  
    td3.innerHTML = "<a href=\"javascript:myjavascript.call(‘"+jsonObj.phone + "‘)\">" + jsonObj.phone + "</a>";   
    }  
  }  
  function getAllLinkMan(){
	  javascript:myjavascript.getAllLinkMan();
  }
  function getSimLinkMan(){
	  javascript:myjavascript.getSimLinkMan();
  }
  function getLinkMan(){
	  javascript:myjavascript.getPhoneLinkMan();
  }
  function getNext(){
	  javascript:myjavascript.getNext();
  }
  
   
</SCRIPT>  
 <BODY onload="javascript:myjavascript.show()">  
   <table width="100%" border="0" cellspacing="0" id="contactTable">  
    <tr>  
      <td width="20%">编号</td>  
      <td width="center">name</td>  
      <td width="30%">phone</td>  
    </tr>  
   </table>  
  <input type="button"  value="获取所有的联系人"  onclick="getAllLinkMan();"/>
  <input type="button"  value="获取多个的联系人"  onclick="getLinkMan();"/>
  <input type="button"  value="获取sim的联系人"  onclick="getSimLinkMan();"/>
  <input type="button"  value="获取单个的联系人" />
  <input type="button"  value="下一个页面" onclick="getNext();"/>
 </BODY>  
</HTML>  

获取联系人信息的一个MyJavaScript类:

package com.stcyclub.testhtmlgetlinkman;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.stcyclub.testhtmlgetlinkman.po.LinkMan;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.PhoneLookup;
import android.sax.StartElementListener;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;

public class MyJavaScript {  
	/**获取库Phon表字段**/  
    private static final String[] PHONES_PROJECTION = new String[] {  
        Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,Phone.CONTACT_ID };  
     
    /**联系人显示名称**/  
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;  
      
    /**电话号码**/  
    private static final int PHONES_NUMBER_INDEX = 1;  
      
    /**头像ID**/  
    private static final int PHONES_PHOTO_ID_INDEX = 2;  
     
    /**联系人的ID**/  
    private static final int PHONES_CONTACT_ID_INDEX = 3;  
      
 
    /**联系人名称**/  
    private ArrayList<String> mContactsName = new ArrayList<String>();  
      
    /**联系人头像**/  
    private ArrayList<String> mContactsNumber = new ArrayList<String>();  
 
    /**联系人头像**/  
    private ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>(); 
    /**保存联系人**/
    private ArrayList<LinkMan> linkMans = new ArrayList<LinkMan>();  
      
	 private final int DIALOG          = 0;
	 private final int REQUEST_CONTACT = 1;
    private WebView webview;  
    //使用一个handler来处理加载事件  
    private Handler handler;  
     private Context mContext;
    public MyJavaScript(Context context,Handler handler){  
        this.handler = handler;  
        webview = (WebView) ((Activity)context).findViewById(R.id.myweb); 
         mContext  =  context;
    }  
    /* 
     * java调用显示网页,异步 
     */  
    public void show(){  
      handler.post(new Runnable() {           
        public void run() {  
       // 重要:url的生成,传递数据给网页  
        String url = "javascript:contactlist(‘" + generateData() + "‘)";  
       webview.loadUrl(url);  
        }  
       });  
    }  
    /* 
     * 由java程序生成数据传到网页中显示 
     */  
    private String generateData(){  
      try {  
        //构造一个json对象  
        JSONObject obj1 = new JSONObject();  
        obj1.put("id", 123);  
        obj1.put("name", "tom");  
        obj1.put("phone", "66666666");  
              
        JSONObject obj2 = new JSONObject();  
        obj2.put("id", 13);  
        obj2.put("name", "jerry");  
        obj2.put("phone", "88888888");  
              
        //将构造好的2个json对象加入到json数组中  
        JSONArray arr = new JSONArray();  
        arr.put(obj1);  
        arr.put(obj2);  
        return arr.toString();  
        } catch (JSONException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return "";  
    }  
    /* 
     * 拨打电话方法 
     */  
    public void call(final String phone){  
          Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + phone));  
          mContext.startActivity(intent);  
    } 
    /**
     * 获取所有的联系人
     */
   
    public void getPhoneLinkMan(){
    	//清空linkMans
    	linkMans.clear();
    	//得到ContentResolver对象
    	//super.onCreate(savedInstanceState);
        ContentResolver cr = mContext.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        //向下移动光标
        while(cursor.moveToNext())
        {
            //取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            String contact = cursor.getString(nameFieldColumnIndex);
           //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            while(phone.moveToNext())
            {
                String Number = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
               // string += (contact + ":" + Number + "");
                LinkMan man=new LinkMan(contact, Number);
                Log.d("TAG",contact + ":" + Number + "");
                linkMans.add(man);
            }
        }
        cursor.close();
        Log.d("TAG", "linkMans.size()"+linkMans.size());
        handler.post(new Runnable() {           
            public void run() {  
           // 重要:url的生成,传递数据给网页  
            String url = "javascript:contactlist(‘" + ObjectToJson() + "‘)";  
            webview.loadUrl(url);  
            }  
           });  
    }
   
    }
    /**
     * 将对象转换成为json数据
     */
    public String ObjectToJson(){
    	 try {    
    	        //将构造好json数组
    	        JSONArray arr = new JSONArray(); 
    	        for(int i =0; i<linkMans.size();i++){
    	        	 //构造一个json对象  
        	        JSONObject obj = new JSONObject();  
        	        obj.put("id", i);  
        	        obj.put("name", linkMans.get(i).getName());  
        	        obj.put("phone", linkMans.get(i).getPhone());
        	        arr.put(obj);  
    	        }
    	        return arr.toString();  
    	        } catch (JSONException e) {  
    	            // TODO Auto-generated catch block  
    	            e.printStackTrace();  
    	        }  
    	        return ""; 
    }
    public void getNext(){
    //	webview.loadUrl("file:///android_asset/index2.html");
    	webview.loadUrl("http://www.baidu.com");
//    	Uri uri=Uri.parse("file:///android_asset/index2.html");
//    	Intent intent=new Intent(Intent.ACTION_VIEW,uri);
//    	mContext.startActivity(intent);
    }
   
}  




MainActivity中的部分代码如下:

public class MainActivity extends Activity {


    private String contactId, contactName;
	 private WebView webView;  
	  private Handler handler = new Handler(); 
	  //自定义的弹出框类  
	    SelectPicPopupWindow menuWindow; 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		init();
	}


	@SuppressLint("JavascriptInterface")
	private void init() {
		 webView = (WebView)findViewById(R.id.myweb);  
	      //重要:让webview支持javascript  
	        webView.getSettings().setJavaScriptEnabled(true);  
	      //重要:添加可以供html中可供javascript调用的接口类  
	       webView.addJavascriptInterface(new MyJavaScript(this, handler), "myjavascript");  
	      //加载index.html  
	      webView.loadUrl("file:///android_asset/index.html");
	}
	public void btnClick(View v){
		//实例化SelectPicPopupWindow  
        menuWindow = new SelectPicPopupWindow(MainActivity.this, itemsOnClick);  
        //显示窗口  
        menuWindow.showAtLocation(MainActivity.this.findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置  
      
	}
	//为弹出窗口实现监听类  
    private OnClickListener  itemsOnClick = new OnClickListener(){  
  
        public void onClick(View v) {  
            menuWindow.dismiss();  
            switch (v.getId()) {  
            
            default:  
                break;  
            }  
        }  
    };  
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("TAG", "requestCode"+requestCode+"\t resultCode"+resultCode+"\t"+data);
		 Uri result = data.getData();
         contactId = result.getLastPathSegment();
         contactName = getPhoneContacts(contactId);
         Toast.makeText(this, "contactName"+contactName, Toast.LENGTH_LONG).show();
    
	}


代码大概就是这样!本人页是初学者,不是很完善。要源码的联系我!

android获取联系人信息

上一篇:hdu 3342 拓扑排序 水


下一篇:android提高进程优先级的方法