Delete contact from android contacts

2019-07-19 16:25发布

问题:

I am trying to delete a contact from phone contacts. The contact gets deleted from phone contacts but it's not getting deleted from the server-side (Google contacts) and when the Google contact sync triggers then that deleted contact re-appears. Below is my code.

public static void deleteContact(long rawid, ContentResolver contentResolver) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    Uri uri = ContactsContract.RawContacts.CONTENT_URI
            .buildUpon()
            .appendQueryParameter(
                    ContactsContract.CALLER_IS_SYNCADAPTER,
                    "true")
            .build();
    ops.add(ContentProviderOperation
            .newDelete(uri)
            .withSelection(
                    ContactsContract.RawContacts._ID + " = ?",
                    new String[]{Long.toString(rawid)})
            .build());

    try {
        contentResolver.applyBatch(
                ContactsContract.AUTHORITY,
                ops);
    } catch (RemoteException | OperationApplicationException e) {
        e.printStackTrace();
    }
} 

回答1:

You should try with ContactsContract.CALLER_IS_SYNCADAPTER as false in your code. While set to true, the contact is permanently deleted from the database. But when the next sync happens the contact is synched back. How Google sync checks for deleted contacts, is using a deleted flag which is set only if you set ContactsContract.CALLER_IS_SYNCADAPTER as false. Below is a snippet of code from the ContactsProvider class (contentprovider for contacts datastore)

if (callerIsSyncAdapter || rawContactIsLocal(rawContactId)) {
    // When a raw contact is deleted, a SQLite trigger deletes the parent contact.
    // TODO: all contact deletes was consolidated into ContactTableUtil but this one can't
    // because it's in a trigger.  Consider removing trigger and replacing with java code.
    // This has to happen before the raw contact is deleted since it relies on the number
    // of raw contacts.
    db.delete(Tables.PRESENCE, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null);
    count = db.delete(Tables.RAW_CONTACTS, RawContacts._ID + "=" + rawContactId, null);
    mTransactionContext.get().markRawContactChangedOrDeletedOrInserted(rawContactId);
} else {
    count = markRawContactAsDeleted(db, rawContactId, callerIsSyncAdapter);
}