我正在尝试以编程方式在Android中添加联系人。这是我的代码:
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,"Google")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME,"user1@gmail.com") .build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract
.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Context ctx = getApplicationContext();
CharSequence txt = "Contact " + name +" added successfully";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(ctx, txt, duration);
toast.show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
}
我这样做是否正确?如何添加帐户名称和帐户类型?
注意:我没有创建任何帐户。是否必须拥有帐户才能添加联系人?
答案 0 :(得分:3)
Contact API storing contact as an invisible contact: How to make it visible?检查一下,我希望它会有用!
无需在手机中创建任何帐户!...我认为他们是默认帐户!
答案 1 :(得分:1)
检查my post有关插入联系人的信息。希望它有所帮助。