程序的主要代码如下:
protected void getContactInfo() {
//获得通讯录信息 ,URI是ContactsContract.Contacts.CONTENT_URI
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
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
Log.v(TAG, "…name…" + name);
//查看给联系人是否有电话,返回结果是String类型,1表示有,0表是没有
String hasPhone = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false";
//如果有电话,根据联系人的ID查找到联系人的电话,电话可以是多个
if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.v(TAG, "…phoneNumber… " + phoneNumber);
}
phones.close();
}
//查找email地址,这里email也可以有多个
Cursor emails = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "
+ contactId, null, null);
while (emails.moveToNext()) {
String emailAddress = emails
.getString(emails
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.v(TAG, "…emailAddress… " + emailAddress);
}
emails.close();
//获得联系人的地址
Cursor address = getContentResolver()
.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID
+ " = " + contactId, null, null);
while (address.moveToNext()) {
// These are all private class variables, don’t forget to create
// them.
String poBox = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = address
.getString(address
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
Log.v(TAG, "…city… " + city);
}
}
cursor.close();
}
AndroidMainfest.xml中添加权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />