Android2.0 中读取联系人——ContactsContract .转

from http://yarin.javaeye.com/blog/523849

 

当我们将Andorid1.5及其以前的项目放到Android2.0上时,如果代码中有

 

1 import android.provider.Contacts;

 

Eclipse会提示“建议不使用”,那是因为在Android2.0中,联系人api发生了变化,需要使用ContactsContract。

 

直接看下面一个最简单的例子,读取联系人的姓名和电话号码:

读取联系人的名字很简单,但是在读取电话号码时,就需要先去的联系人的ID,然后在通过ID去查找电话号码!一个联系人可能存在多个电话号码!

 

		//得到ContentResolver对象
        ContentResolver cr = getContentResolver();  
        //取得电话本中开始一项的光标
		Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

		while (cursor.moveToNext())
		{
			// 取得联系人名字
			int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
			String name = cursor.getString(nameFieldColumnIndex);
			string += (name);

			// 取得联系人ID
			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 strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				string += (":" + strPhoneNumber);
			}
			string += "\n";
			phone.close();
		}
		cursor.close();

 

 当然,还有得到email等操作!

 先写到这里,更多关于Android2.0的内容,有待研究。

posted on 2010-07-08 15:35  boby house  阅读(282)  评论(0编辑  收藏  举报