以编程方式更改联系人姓名

时间:2017-09-19 12:49:54

标签: android android-contentprovider android-contentresolver

我正在尝试以编程方式更改特定联系人(通过contactId)显示名称。 我在这里研究了类似的q& a并尝试了以下内容:

public static boolean updateContactName(Context context, long contactId, String newName) {
    try {
        ContentResolver contentResolver  = context.getContentResolver();

        ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
        ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
                                Data.MIMETYPE + "='" +
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
                        new String[]{Long.toString(contactId)})
                .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, newName)
                .build());

        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
        return true;
    } catch (Exception e) {
        CLog.d(ContactUtils.class, e);
        return false;
    }
}

它正在某些设备上运行,但在其他设备上(例如LG G3),它无法正常工作,没有更新。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

请查看:

try {
    String newName = txtName.getText();
    ArrayList<ContentProviderOperation> cpoList = new ArrayList<ContentProviderOperation>();

    cpoList.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
    .withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
           Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'", new String[]{contact_id})
    .withValue(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, newName)
    .build());
    ContentProviderResult[] result = getContentResolver().applyBatch(ContactsContract.AUTHORITY, cpoList);
} catch (Exception e) {
    // Do Any thing
}