androidgoogle-play-servicesandroid-contactsdevice-adminandroid-work-profile

How do I disable a syncadapter or provider as Device Admin programmatically?


I need to write an App that can prevent contact syncing in a work profile. Until Android 9 i just disabled the package com.google.android.syncadapters.contacts and that's it.

Unfortunately since Android 10 the Play Services are responsible for syncing contacts from a Google Account. But I don't want to disable the package com.google.android.gms in the work profile since that has many more side effects.

So I'm currently searching a way or an API to disable a specific component of another app as a device admin or owner of a work profile.

Thanks and Regards, David


Solution

  • I have 3 methods to try and accomplish this, never tested them though:

    Solution 1 - setSyncAutomatically:

    Account[] accounts = AccountManager.get(this).getAccountsByType(theAccountType);
    for (Account account : accounts) {
        Log.d(TAG, "got " + account.type + " / " + account.name);
        ContentResolver.setSyncAutomatically(account,ContactsContract.AUTHORITY,false); // disable auto-syncing on that sync-adapter
    

    ContentResolver.setIsSyncable(account,ContactsContract.AUTHORITY,false); // disable periodic sync as well }

    Solution 2 - removeAccountExplicitly:

    I think that, depending on your target API Android might throw an exception if you're trying to disable a sync adapter that doesn't belong to your own app (i.e. signed using a different certificate). However, it's worth a shot to try out.

    Account[] accounts = AccountManager.get(this).getAccountsByType(theAccountType);
    for (Account account : accounts) {
        Log.d(TAG, "got " + account.type + " / " + account.name);
        AccountManager.removeAccountExplicitly(account); // completely removing the account, not just disabling sync... beware.
    }
    

    Solution 3 - launch syncadapter's settings screen:

    The second best option you have, would be to launch the specific settings screen to allow the user to quickly disable sync with a single click:

    final SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
    for (SyncAdapterType sync : syncs) {
        Log.d(TAG, "found SyncAdapter: " + sync.accountType);
        if (theAccountType.equals(sync.accountType)) {
            Log.d(TAG, "found it: " + sync);
            String activityStr = sync.getSettingsActivity();
            Intent intent = new Intent(Intent.ACTION_VIEW, activityStr);
            // launch the intent
        }
    }