androidandroid-contentresolverandroid-syncadapter

Why ContentResolver.cancelSync() doesn't cancel SyncAdapter syncing process?


How to cancel SyncAdapter syncing process? ContentResolver.cancelSync() doesn't cancel it.

I need it because I sync a thousand contacts (in onPerformSync()) from the app to Android Contact book (invoking ContentResolver.requestSync()). And I need to cancel current syncing when i want to perform new one.

To check one more time that ContentResolver.cancelSync() doesn't cancel syncing I donwloaded BasicSyncAdapter. Replaced onPerformSync() with

@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    for (int i = 0; i < 20; i ++) {
        if (i == 10) {
            ContentResolver.cancelSync(GenericAccountService.GetAccount(ACCOUNT_TYPE), FeedContract.CONTENT_AUTHORITY);
        }
        Log.i(TAG, "count " + i);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

So after 10 it must stop but it logging all 20.

Thank you!


Solution

  • The documentation of AbstractThreadedSyncAdapter has a section on cancellation:

    A sync is cancelled by issuing a Thread.interrupt() on the syncing thread. Either your code in onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult) must check Thread.interrupted(), or you you must override one of onSyncCanceled(Thread)/onSyncCanceled() (depending on whether or not your adapter supports syncing of multiple accounts in parallel). If your adapter does not respect the cancel issued by the framework you run the risk of your app's entire process being killed.