如何以编程方式添加联系人

时间:2015-03-10 10:14:54

标签: android

如何使用编程添加联系人我正在尝试这个:

public void addContact(Contact contact)
    ContentValues values = new ContentValues();
    values.put("contact_id", contact.getContactId());
    values.put("lookup", contact.getLookupKey());
    values.put("mimetype", StructuredName.CONTENT_ITEM_TYPE);
    values.put("data1", contact.getStructuredName().getDisplayName());
    values.put("data2", contact.getStructuredName().getGivenName());
    values.put("data3", contact.getStructuredName().getFamilyName());
    values.put("data4", contact.getStructuredName().getPrefix());
    values.put("data5", contact.getStructuredName().getMiddleName());
    values.put("data6", contact.getStructuredName().getSuffix());
    context.getContentResolver().insert(Data.CONTENT_URI, values);
    }

1 个答案:

答案 0 :(得分:8)

执行此操作的最佳方法是使用ContentProviderOperation,而不是使用ContentValues。使用该功能:

private void addContact() {
    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); 
    operationList.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) 
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) 
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) 
            .build()); 

    // first and last names 
    operationList.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) 
            .withValueBackReference(Data.RAW_CONTACT_ID, 0) 
            .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) 
            .withValue(StructuredName.GIVEN_NAME, "Second Name") 
            .withValue(StructuredName.FAMILY_NAME, "First Name") 
            .build()); 

    operationList.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) 
            .withValueBackReference(Data.RAW_CONTACT_ID, 0) 
            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "09876543210")
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_HOME)
            .build());
    operationList.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) 
            .withValueBackReference(Data.RAW_CONTACT_ID, 0)

            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Email.DATA, "abc@xyz.com")
            .withValue(ContactsContract.CommonDataKinds.Email.TYPE, Email.TYPE_WORK)
            .build());

    try{ 
        ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList); 
    }catch(Exception e){ 
        e.printStackTrace(); 
    } 
}

注意:请将其导入您的班级文件import android.provider.ContactsContract.Data;

祝你好运。