android 中获取通讯录中联系人信息,代码如下:
/**
* 获取联系人信息,包括:名称、号码、头像
* @return
*/
private ArrayList<PhoneContactor> getPhoneContacts(){
Log.i(TAG, "getPhoneContacts");
ContentResolver resolver=this.getContentResolver();
ArrayList<PhoneContactor> list = new ArrayList<PhoneContactor>();
String[] columns = new String[] {Phone.DISPLAY_NAME,Phone.NUMBER,Phone.PHOTO_ID,Phone.CONTACT_ID};
Cursor cursor = resolver.query(Phone.CONTENT_URI, columns, null,null, null);
Bitmap photo_default=BitmapFactory.decodeResource(getResources(), R.drawable.contact_photo_default);
while (cursor.moveToNext()) {
PhoneContactor pc = new PhoneContactor();
String name=cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
String number=cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
if(TextUtils.isEmpty(number)){ //判断号码是否为空
continue;
}
long photoId=cursor.getLong(cursor.getColumnIndex(Phone.PHOTO_ID));
long contactId=cursor.getLong(cursor.getColumnIndex(Phone.CONTACT_ID));
//得到联系人头像Bitamp
Bitmap contactPhoto = null;
//photoId 大于0表示联系人有头像,否则设置一个默认头像
if(photoId > 0 ) {
Uri uri =ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
contactPhoto = BitmapFactory.decodeStream(input);
}else {
contactPhoto = photo_default;
}
pc.name(name);
pc.number(number);
pc.photo(contactPhoto);
list.add(pc);
Log.d(TAG, "name:" + pc.name());
Log.d(TAG, "number:" + pc.number());
}
cursor.close();
return list;
}
其中:PhoneContactor为自定义的存储联系人信息的类,最后别忘了加上权限:
<uses-permission android:name="android.permission.READ_CONTACTS"/>