Android更改联系人图片

时间:2011-11-01 14:41:21

标签: android android-intent contacts

我正在构建一个应用程序,当点击图像时,用户会看到联系人列表并选择一个。点击后,它的联系人图片应该更改为首先点击的图像。 以下是我实现它的方法:

....
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, SELECT_CONTACT);
.....
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_CONTACT) {
                Uri contactData = data.getData();
                ????? what should come here???
            }
        }
    }

我的问题是如何访问和更改联系人图片? 谢谢

1 个答案:

答案 0 :(得分:10)

首先,获取联系人第一次原始联系人的Uri:

Uri rawContactUri = null;
Cursor rawContactCursor =  managedQuery(
        RawContacts.CONTENT_URI, 
        new String[] {RawContacts._ID}, 
        RawContacts.CONTACT_ID + " = " + contactData.getLastPathSegment(), 
        null, 
        null);
if(!rawContactCursor.isAfterLast()) {
    rawContactCursor.moveToFirst();
    rawContactUri = RawContacts.CONTENT_URI.buildUpon().appendPath(""+rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();

然后,将位图转换为字节数组:

Bitmap bit; // <-- put your bitmap here
ByteArrayOutputStream streamy = new ByteArrayOutputStream(); 
bit.compress(CompressFormat.PNG, 0, streamy); 
byte[] photo = streamy.toByteArray();

最后,将字节数组设置为原始联系人的照片:

ContentValues values = new ContentValues(); 
int photoRow = -1; 
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " + 
    ContentUris.parseId(rawContactUri) + " AND " + Data.MIMETYPE + "=='" + 
    ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'"; 
Cursor cursor = managedQuery(
        ContactsContract.Data.CONTENT_URI, 
        null, 
        where, 
        null, 
        null); 
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID); 
if(cursor.moveToFirst()){ 
    photoRow = cursor.getInt(idIdx); 
} 
cursor.close(); 
values.put(ContactsContract.Data.RAW_CONTACT_ID, 
        ContentUris.parseId(rawContactUri)); 
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1); 
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo); 
values.put(ContactsContract.Data.MIMETYPE, 
        ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE); 
if(photoRow >= 0){ 
    this.getContentResolver().update(
            ContactsContract.Data.CONTENT_URI, 
            values, 
            ContactsContract.Data._ID + " = " + photoRow, null); 
    } else { 
        this.getContentResolver().insert(
                ContactsContract.Data.CONTENT_URI, 
                values); 
    } 
} 

修改

请确保在清单中包含以下两项权限:

<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>