首先,得到的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"/>
感謝您的意見,但我的應用程序chashes當它執行的代碼 – maephisto
哪條線的第一部分,什麼是錯誤的文字? – Krylez
當我更改照片時,照片發生了變化,我可以在電話簿應用中看到它。但幾秒鐘後會自動恢復(如果沒有以前的照片,則刪除)。我懷疑這與Google帳戶同步有關。任何想法如何解決它? – cprcrack