通过URI获取联系人照片

时间:2013-09-09 14:51:03

标签: android

我的android函数返回URI,如下所示: content://com.android.contacts/contacts/@some number@

当我知道URI时,如何获取此联系人的照片?

修改
为什么以下代码不起作用:

  Uri test = Uri.parse("content://com.android.contacts/contacts/227");
  row.setImageViewUri(android.R.id.icon, test);

1 个答案:

答案 0 :(得分:2)

你应该使用这种方法:

 public Uri getPhotoUri() {
try {
    Cursor cur = this.ctx.getContentResolver().query(
            ContactsContract.Data.CONTENT_URI,
            null,
            ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
                    + ContactsContract.Data.MIMETYPE + "='"
                    + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
            null);
    if (cur != null) {
        if (!cur.moveToFirst()) {
            return null; // no photo
        }
    } else {
        return null; // error in cursor process
    }
} catch (Exception e) {
    e.printStackTrace();
    return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
        .parseLong(getId()));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}

用法是:

Uri u = objItem.getPhotoUri();
if (u != null) {
    mPhotoView.setImageURI(u);
} else {
    mPhotoView.setImageResource(R.drawable.ic_contact_picture_2);
}