问题
When a contact is updated with batch operation "context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);"
then other apps like WhatsApp does not take updates automatically.
For example, If mobile number is updated/removed as:-
String deviceNumber= "+1 (234) 56789";
String oldTrimmed= "+123456789";
String where = ContactsContract.CommonDataKinds.Phone.NUMBER + " = ? OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " = ? AND " + ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] args = {oldTrimmed, deviceNumber, contactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(where, args)
.build()
);
then old number is still displayed in mobile as whatsApp number.
Is there any way to trigger sync for mobile contacts after any updation sothat other apps can be also synced automatically.
回答1:
while updating contact information programmatically, you should also trigger sync so that all adapter can be synchronized.
This can be done as following:-
private void requestSync()
{
AccountManager am = AccountManager.get(context);
Account[] accounts = am.getAccounts();
for (Account account : accounts)
{
int isSyncable = ContentResolver.getIsSyncable(account, ContactsContract.AUTHORITY);
if (isSyncable > 0)
{
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(accounts[0], ContactsContract.AUTHORITY, extras);
}
}
}
This code will get the accounts which are added to contact app of the device such as "WhatsApp" and "Google" and will request to synchronize.
Permissions should be added as
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
来源:https://stackoverflow.com/questions/61454841/android-programmatically-updated-contact-is-not-syncing-with-other-apps