本文介绍了通过ContactsContract和ContentProvider添加带有照片的新联系人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在努力将带有照片的联系人添加到Android通讯录中.最后,我要添加图片以进行联系,但是我无法添加任何姓名或电话号码.联系人显示为(未知)",并带有适当的照片.
I've been trying all day to add contact with photo to Android Contacts. Finally I'm adding picture to contact, but I can't add any name or phone number. Contact is displaying as "(Unknown)", with proper photo.
我的代码:
private void addContact2() {
final String displayName = "XYZA";
final String mobileNumber = "666666";
final byte[] photoByteArray; // initalized elsewhere
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
//.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray)
.build());
Uri newContactUri = null;
ContentProviderResult[] res = null;
try {
final ContentResolver contentResolver = getContentResolver();
res = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
if (res != null && res.length > 0 && res[0] != null) {
newContactUri = res[0].uri;
Log.d(CallActivity.class.getName(), "URI added contact:"+ newContactUri);
Toast.makeText(this, "Successfully added " + displayName, Toast.LENGTH_LONG).show();
}
else Log.e(CallActivity.class.getName(), "Contact not added.");
} catch (NullPointerException | RemoteException | OperationApplicationException e) {
Log.e(CallActivity.class.getName(), e.getMessage(), e);
}
}
推荐答案
好,我已经解决了.在名称" ops.add上,我写了.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
而不是.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.现在一切正常.
Ok, I've fixed it. On "name" ops.add I wrote .withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
instead of .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
. Now everything works fine.
这篇关于通过ContactsContract和ContentProvider添加带有照片的新联系人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!