1.先申请读取通讯录权限
Manifest.permission.READ_CONTACTS,
2.获取通讯录信息
public ArrayList<MyContacts> getAllContacts() {
ArrayList<MyContacts> contacts = new ArrayList<MyContacts>();
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
//新建一个联系人实例
MyContacts temp = new MyContacts();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//获取联系人姓名
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
temp.setName(name);
temp.setUserId(contactId);
//获取联系人电话号码
Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
while (phoneCursor.moveToNext()) {
String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phone = phone.replace("-", "");
phone = phone.replace(" ", "");
temp.setNumber(phone);
}
//获取联系人备注信息
Cursor noteCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID, ContactsContract.CommonDataKinds.Nickname.NAME},
ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE + "'",
new String[]{contactId}, null);
if (noteCursor.moveToFirst()) {
do {
String note = noteCursor.getString(noteCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));
// temp.note = note;
Log.i("note:", note);
} while (noteCursor.moveToNext());
}
contacts.add(temp);
//记得要把cursor给close掉
phoneCursor.close();
noteCursor.close();
}
cursor.close();
return contacts;
}
附:MyContacts的JavaBean
public class MyContacts {
private String name;
private String number;
private String userId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "MyContacts{" +
"name='" + name + '\'' +
", number='" + number + '\'' +
", userId='" + userId + '\'' +
'}';
}
}
4.获取通讯录其他信息 请参考:http://www.360doc.com/content/13/0708/12/12890102_298446854.shtml