您的位置:首页 > 移动开发 > Android开发

android 获取通讯录联系人信息

2012-08-29 13:35 525 查看
  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"/> 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息