ContactsContract获取联系人信息

一、 从Android 2.0 SDK开始有关联系人provider的类变成了ContactsContract,虽然老的android.provider.Contacts能用,但是在SDK中标记为为deprecated将被放弃不推荐的方法,而从Android 2.0及API Level为5开始新增了android.provider.ContactsContract来代替原来的方法。
ContactsContract的子类ContactsContract.Contacts是一张表,代表了所有联系人的统计信息。比如联系人ID(—ID),查询键(LOOKUP_KEY),联系人的姓名(DISPLAY_NAME_PRIMARY),头像的id(PHOTO_ID)以及群组的id等等。

我们可以通过以下的方法取得所有联系人的表的Cursor对象:
1)ContentResolver contentResolver=getContentResolver();//获取 ContentResolver对象查询在ContentProvider里定义的共享对象;

2)Cursor cursor=contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
   //根据URI对象ContactsContract.Contacts.CONTENT_URI查询所有联系人;

从Cursor对象里我们关键是要取得联系人的_id。通过它,再通过ContactsContract.CommonDataKinds的各个子类查询该_id联系人的电话(ContactsContract.CommonDataKinds.Phone),email(ContactsContract.CommonDataKinds.Email)等等。
以取得该联系人所有电话为例:
1)int idFieldIndex=cursor.getColumnIndex(ContactsContract.Contacts._ID);
   int id=cursor.getInt(idFieldIndex);//根据列名取得该联系人的id;
2)Cursor phonecursor=contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?", new String[]{Integer.toString(id)}, null);
 //再类ContactsContract.CommonDataKinds.Phone中根据查询相应id联系人的所有电话;
类似地可以ContactsContract.CommonDataKinds的不同的子类查询不同的内容。android文档告诉我们推荐使用ContactsContract.Contacts.LOOKUP_KEY代替ContactsContract.Contacts._ID。

最后,由于读取联系人比较的占用资源,为了提高用户的体验度。考虑将读取的过程放在线程里完成,推荐使用AsyncTask类。

二、

在2.1中,display_name 在contact表中,而data表中包含很多contact的数据,比如电话,姓名,email等 ,如果要查询一个联系人的姓名和电话,网上大多数的做法是:
先查contact表,得到姓名,再根据has_phone_number是否是1决定data表中有无电话记录。这样是要查发2个uri,得到两个cursor在分别去除需要的内容。
其实可以直接发一个uri就查处姓名和号码,代码:
Cursor c=getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, "mimetype='vnd.android.cursor.item/phone_v2'", null, null);
这个uri对象data,他会去查view_data这个试图,试图定义就是data,raw_contacts,mimetypes,group等一系列表的联合查询,而上面这个uri发出去会得到很多字段,当条件为mimetype=vnd.android.cursor.item/phone_v2则查的是此人电话所对应的那条记录,其中也会得到姓名,
注意:
姓名是根据display_name 取得
电话是根据data1取得

Example1:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Uri contactsUri=ContactsContract.Contacts.CONTENT_URI;
        String[] proj1=new String[]{ContactsContract.Contacts.DISPLAY_NAME,
                                    ContactsContract.Contacts.HAS_PHONE_NUMBER,
                                    ContactsContract.Contacts.LOOKUP_KEY};
        Cursor curContacts=getContentResolver().query(contactsUri,proj1, null, null, null);
           
         ArrayList<String> contactsList=new ArrayList<String>(); 
        String allPhoneNo="";
        if(curContacts.getCount()>0){
            while(curContacts.moveToNext()){   
                // get all the phone numbers if exist
                if(curContacts.getInt(1)>0){
                    allPhoneNo=getAllPhoneNumbers(curContacts.getString(2));
                }
                contactsList.add(curContacts.getString(0)+" , "+allPhoneNo);
                allPhoneNo="";
            }
        }
   
        // binding the data to ListView 
        setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, contactsList));
        ListView lv=getListView();
        lv.setTextFilterEnabled(true);
        
    }
    
    /**
     * Get all the phone numbers of a specific contact person    
     */
    public String getAllPhoneNumbers(String lookUp_Key){
        String allPhoneNo="";
        
        // Phone info are stored in the ContactsContract.Data table 
        Uri phoneUri=ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] proj2={ContactsContract.CommonDataKinds.Phone.NUMBER};
        // using lookUp key to search the phone numbers
        String selection=ContactsContract.Data.LOOKUP_KEY+"=?";

        Cursor cur=getContentResolver().query(phoneUri,proj2,selection, new String[]{lookUp_Key}, null);
        while(cur.moveToNext()){
            allPhoneNo+=cur.getString(0)+" ";
        }

        return allPhoneNo;        
    }

来源:http://www.cnblogs.com/ruiyi1987/archive/2011/06/20/2084925.html

Example2:

private List<HashMap<String, String>> fillMaps() {
		List<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();

		Cursor cur = null;
		try {
			// Query using ContentResolver.query or Activity.managedQuery
			cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
			if (cur.moveToFirst()) {
				int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);
				int displayNameColumn = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
				// Iterate all users
				do {
					String phoneNumber = "";
					String contactId = cur.getString(idColumn);
					String displayName = cur.getString(displayNameColumn);
					// Get number of user's phoneNumbers
					int numberCount = cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
					if (numberCount > 0) {
						Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId
						/*
						 * + " and " + ContactsContract.CommonDataKinds
						 * .Phone.TYPE + "=" + ContactsContract.CommonDataKinds
						 * .Phone.TYPE_MOBILE
						 */, null, null);
						if (phones.moveToFirst()) {
							int numberColumn = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
							do {
								phoneNumber += phones.getString(numberColumn) + ",";
							} while (phones.moveToNext());
						}
					}
					// Add values to items
					HashMap<String, String> i = new HashMap<String, String>();
					i.put("name", displayName);
					i.put("key", phoneNumber);
					items.add(i);
				} while (cur.moveToNext());
			} else {
				HashMap<String, String> i = new HashMap<String, String>();
				i.put("name", "Your Phone");
				i.put("key", "Have No Contacts.");
				items.add(i);
			}
		} finally {
			if (cur != null)
				cur.close();
		}
		return items;
	}

来源:http://www.apkbus.com/android-14565-1-1.html

猜你喜欢

转载自uule.iteye.com/blog/1709227