使用LOOKUP_URI在Android(API 8)中获取联系人照片
我试图使用其查找URI来获取联系人图像。 我成功使用此代码获取DISPLAY_NAME:使用LOOKUP_URI在Android(API 8)中获取联系人照片
Cursor c = context.getContentResolver().query(contactLookupUri,
new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null,
null, null);
但我没有找到一种方式来获得的照片。该Photo.PHOTO选项不适用于我使用,并试图用一个InputStream没有工作,以及得到它的API(也许是我做错了什么那里):
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(),
contactUri);
谢谢, 约尔
最后,我要解决它获取联系人ID和使用inputStream:
public static Uri getContactLookupUri(String contactLookupKey) {
return Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI, contactLookupKey);
}
public static Bitmap getContactImage(Context context, String contactLookupKey) {
long contactId;
try {
Uri contactLookupUri = getContactLookupUri(contactLookupKey);
Cursor c = context.getContentResolver().query(contactLookupUri,
new String[] { ContactsContract.Contacts._ID }, null, null,
null);
try {
if (c == null || c.moveToFirst() == false) {
return null;
}
contactId = c.getLong(0);
} finally {
c.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri contactUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(),
contactUri);
if (input != null) {
return BitmapFactory.decodeStream(input);
} else {
return null;
}
}
下面这个函数返回你的CONTACT_ID的图像URI
/**
* @return the photo URI
*/
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);
}
也可参考此LINK
嗨Agarwal,谢谢你的答案,但我没有联系人ID,我只有lookupKey。我实际上不明白你的解决方案,因为它似乎根本没有使用查询的结果。 – yoel 2012-04-21 08:30:44
@yoel你可以发布你的源代码吗?我不明白“Uri contactLookupUri = getContactLookupUri(contactLookupKey);” – SpicyWeenie 2012-04-29 09:14:37
什么是“contactLookupKey?” – SpicyWeenie 2012-04-29 08:56:27
lookupKey的解释可以在这里找到:http://developer.android.com/resources/articles/contacts.html – yoel 2012-04-29 16:02:46