讲到获取Contacts的名字和号码,首先给大家简单介绍一下两个类ContentProvider和ContentResolver。一般我们都用ContentResolver类中的一些方法来处理ContentProvider暴露出来的数据,在Contacts方面这些数据主要有CONTENT_URI(管理联系人的uri),Phone.CONTENT_URI(管理联系人电话的uri),Email.CONTENT_URI(管理联系人email的uri)。使用ContentResolver来操作这些数据只要两步:第一,调用Activity的getContentResolver()来获取ContentResolver对象。
第二,根据需要调用ContentResolver中的insert(),delete(),update(),query()方法操作数据即可。
调用:
ContentResolver cr = AddGesture.this.getContentResolver();
操作数据,以query为例:
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI
, null, null, null, null);
// 遍历查询结果,获取系统中所有联系人
while (cursor.moveToNext())
{
// 获取联系人ID
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
// 获取联系人的名字
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
names.add(name);
// 使用ContentResolver查找联系人的电话号码
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
ArrayList<String> detail = new ArrayList<String>();
// 遍历查询结果,获取该联系人的多个电话号码
while (phones.moveToNext())
{
// 获取查询结果中电话号码列中数据。
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract
.CommonDataKinds.Phone.NUMBER));
detail.add("电话号码:" + phoneNumber);
}
phones.close();
也可以通过联系人的名字来查找号码,只要更改query()方法中的参数即可:
Cursor android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
改变第三和第四个参数:
String[] projection = new String[]
{ContactsContract.CommonDataKinds.Phone.NUMBER};
cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + "=?", new String[]{name}, "");
第四个参数就是所要搜索的名字,projection是A list of which columns to return. Passing null will return all columns, which is inefficient.返回的数据列表,本代码只返回电话号码,如果将其设置为null,则返回所有的列表,这个效率不高,所以一般都会设置。