Home » Android » how to sync phone contacts into gmail in android programmatically using google contacts api

how to sync phone contacts into gmail in android programmatically using google contacts api

Posted by: admin June 15, 2020 Leave a comment

Questions:

How to synchronize Android native contacts into Google account using Google API.
Provide some useful links.

How to&Answers:

The syncing happens automatically. You can add or delete contacts programatically. But the syncing is handled by the OS automatically if and only if the user has enabled ‘sync conatcts’ option in phone settings.

You can, however run a sync routine that can call the syncing process if syncing is enabled by the user using something like this:

private void requestSync()
{
    AccountManager am = AccountManager.get(this);
    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);
        }
    }
}

Answer:

The following could also be a good answer. Its similar to the above one, but default Settings app uses code something like this:

private void requestSyncForAccounts() {
    SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes();
    Bundle extras = new Bundle();
    extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    Account[] accounts = AccountManager.get(PeopleActivity.this).getAccounts();
    for (Account account : accounts) {
        for (int j = 0; j < syncAdapters.length; j++) {
            SyncAdapterType sa = syncAdapters[j];
            if (ContentResolver.getSyncAutomatically(account, sa.authority)) {
                ContentResolver.requestSync(account, sa.authority, extras);
            }
        }
    }
}