为什么我不能从联系号码获取个人资料图片的URI?

时间:2012-04-29 11:19:31

标签: android imageview uri photo contact

我有一个自定义来电屏幕,可以显示来电的姓名和电话号码。如果联系人设置了个人资料照片(在您自己的手机上),该图像应显示在我创建的ImageView中。任何不在手机上的号码都会显示Android图标。

在测试代码后,无论电话号码是否存储在手机(模拟器)上,我都会获得Android图标。以下是检索呼叫者联系人照片的代码(如果有的话):

public Uri getPhotoUri(long contactId) { //contactId takes the phone number.

    ContentResolver contentResolver = getContentResolver();

    try {
        Cursor cursor = contentResolver
            .query(ContactsContract.Data.CONTENT_URI,
                null,
                ContactsContract.Data.CONTACT_ID
                    + "="
                    + contactId
                    + " AND "

                    + ContactsContract.Data.MIMETYPE
                    + "='"
                    + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                    + "'", null, null);

        if (cursor != null) {
        if (!cursor.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, contactId);
    return Uri.withAppendedPath(person,
        ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
  }

此方法调用上述方法,并将图片分配给ImageView。问题是else语句总是执行:

IncomingCallListener.getId(的getID)));是用于获取相应个人资料照片的实际电话号码。

public void showContactPhoto(){

    Uri u = getPhotoUri(IncomingCallListener.getId(getID()));
    if (u != null) {    
        qcbContactPic.setImageURI(u);
        Log.d("PHOTO", "ID launched");
    } else {
        qcbContactPic.setImageResource(R.drawable.ic_launcher);
        Log.d("PHOTO", "Default launched");
    }
}

有没有人对为什么“你”保持无效有任何想法?

注意:联系人图片存储在媒体库中。

1 个答案:

答案 0 :(得分:0)

试试这个

Uri uri = ContentUris.withAppendedId(
                    ContactsContract.Contacts.CONTENT_URI, longId);
            ContentResolver cr = getContentResolver();
            InputStream input = ContactsContract.Contacts
                    .openContactPhotoInputStream(cr, uri);
            if (input == null) {
                return null;
            } else
                return BitmapFactory.decodeStream(input);

使用ImageView的setImageBitmap()方法。

相关问题