People 类目前已被弃用。您必须使用ContactsConstract。
有一个例子:
/**
* Research all contacts from "Contacts" table
* @return List<Contact>
*/
public List<Contact> getAllContacts() {
List<Contact> returnList = new ArrayList<Contact>();
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.STARRED,
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + "1" + "'";;
String[] selectionArgs = null;
String sortOrder = /*ContactsContract.Contacts.STARRED + " DESC , " +*/ ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = _context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
cursor.moveToFirst();
//For each contact
while(!cursor.isAfterLast()) {
Integer columnID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
Integer columnName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
Integer columnStarred = cursor.getColumnIndex(ContactsContract.Contacts.STARRED);
Contact contact = new Contact();
contact.setId(cursor.getInt(columnID));
contact.setName(cursor.getString(columnName));
contact.setFavourite(Boolean.parseBoolean(cursor.getString(columnStarred)));
returnList.add(contact);
cursor.moveToNext();
}
return returnList;
}
要检索电话号码,您应该使用另一个 CONTENT_URI。
/**
* Return all the phones for a specific contact
* @param id Row "CONTACT_ID" of the table Contacts
* @return Map<Integer, String>
*/
private SparseArray<String> getPhones(Integer id) {
SparseArray<String> phonesMap = new SparseArray<String>();
//Research all the phones number
Cursor phones = _context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, null, null);
Log.d(this.getClass().getName(),String.valueOf(phones.getCount()));
phones.moveToFirst();
//Foreach phone number
while(!phones.isAfterLast()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
int phoneType = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if(phoneType==ContactsContract.CommonDataKinds.Phone.TYPE_HOME) {
phonesMap.put(ContactsContract.CommonDataKinds.Phone.TYPE_HOME, phoneNumber);
}
if(phoneType==ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
phonesMap.put(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, phoneNumber);
}
if(phoneType==ContactsContract.CommonDataKinds.Phone.TYPE_WORK) {
phonesMap.put(ContactsContract.CommonDataKinds.Phone.TYPE_WORK, phoneNumber);
}
phones.moveToNext();
}
phones.close();
return phonesMap;
}