如何以编程方式在Android手机上添加多个号码的联系人?
答案 0 :(得分:3)
这就是我们如何做到这一点
将Name和Number of number传递给此方法。
public static void addToContactList(Context context, String strDisplayName, String[] strNumber) throws Exception {
ArrayList<ContentProviderOperation> cntProOper = new ArrayList<>();
int contactIndex = cntProOper.size();//ContactSize
ContentResolver contactHelper = context.getContentResolver();
cntProOper.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)//Step1
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
//Display name will be inserted in ContactsContract.Data table
cntProOper.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)//Step2
.withValueBackReference(android.provider.ContactsContract.Data.RAW_CONTACT_ID, contactIndex)
.withValue(android.provider.ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, strDisplayName) // Name of the contact
.build());
for (String s : strNumber) {
//Mobile number will be inserted in ContactsContract.Data table
cntProOper.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)//Step 3
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, contactIndex)
.withValue(android.provider.ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, s) // Number to be added
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build()); //Type like HOME, MOBILE etc
}
ContentProviderResult[] s = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, cntProOper); //apply above data insertion into contacts list
for (ContentProviderResult r : s) {
Log.i(TAG, "addToContactList: " + r.uri);
}
}