How to remove a contact programmatically in android

前端 未结 7 1350
梦毁少年i
梦毁少年i 2020-11-28 08:49

I try the following code to remove contact with a specified number:

private void removeContact(Context context, String phone) {
    //context.getContentResol         


        
7条回答
  •  醉话见心
    2020-11-28 09:21

    This is all we need. To delete Contact with phone number and name given

    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());
        } finally {
            cur.close();
        }
        return false;
    }
    

    And remind to add read/write contact permission

    
    
    

提交回复
热议问题