以编程方式删除所有联系人

时间:2013-06-06 13:28:11

标签: android contacts

删除所有联系人方法似乎是这样做的:

ContentResolver contentResolver = myActivity.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null,  null, null);
while (cursor.moveToNext()) {
       String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
       Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
       contentResolver.delete(uri, null, null);
}

有没有办法调整此项来删除RawContacts而不是联系人?像这样:

ContentResolver contentResolver = myActivity.getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, null, null);
        }

我正在寻找其他方法来删除所有联系人。清除所有联系人表格(联系人,原始联系人,数据)的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

在for循环中,你调用下面的方法,

这就是我们所需要的。 删除联系人电话号码和姓名

public static boolean deleteContact(Context ctx, String phone, String name) {
    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
    try {
        if (cur.moveToFirst()) {
            do {
                if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                    ctx.getContentResolver().delete(uri, null, null);
                    return true;
                }

            } while (cur.moveToNext());
        }

    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    }
    return false;
}

并提醒添加读/写联系人权限

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />