首先使用ContentProviderOperation的方式來插入新的聯繫人。
final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
Bitmap bmp = YCardImageLoader.getInstance().getBitmapByCache(mTask.getImageUrl());
if (bmp != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, 0)
.withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE)
.withValue(Photo.PHOTO, bytes)
.build());
}
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, 0)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, mContact.getName())
.build());
ContentProviderResult[] result = SaveToPbkActivity.this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
然後得到結果URI作爲ACTION_EDIT URI,把其他額外,startActivityForResult(意向,REQUEST_INSERT_CONTACT)。
Intent editIntent = new Intent(Intent.ACTION_EDIT);
uri = result[0].uri;
editIntent.setDataAndType(uri, Contacts.CONTENT_ITEM_TYPE);
editIntent.putExtra("finishActivityOnSaveCompleted", true);
putExtras(editIntent, null);
startActivityForResult(editIntent, REQUEST_INSERT_CONTACT);
,因爲我們第一次插入,我們將刪除它時,resultCode爲!= RESULT_OK
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_INSERT_CONTACT) {
if (resultCode == RESULT_OK) {
//SAVE SUCCESS
} else {
ContentResolver cr = getContentResolver();
cr.delete(uri, null, null);
}
} }
最後對不起,我的英語!