需要读取通讯录权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
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;
}
ArrayList<MyContacts> allContacts = getAllContacts();
for (int i = 0; i < allContacts.size(); i++) {
System.out.println(" 通讯录好友id "allContacts.get(i).getUserId()+" name "+allContacts.get(i).getName()+" number "+allContacts.get(i).getNumber());
}
|