为什么 ContentResolver.cancelSync() 不取消 SyncAdapter 同步进程?

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

如何取消SyncAdapter同步进程? ContentResolver.cancelSync() 不会取消它。

我需要它,因为我将一千个联系人(在 onPerformSync() 中)从应用程序同步到 Android 通讯录(调用 ContentResolver.requestSync())。当我想执行新的同步时,我需要取消当前的同步。

为了再次检查 ContentResolver.cancelSync() 不会取消同步,我下载了 BasicSyncAdapter。将 onPerformSync() 替换为

@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();
        }
    }
}

所以在 10 之后它必须停止但它记录所有 20。

谢谢!

AbstractThreadedSyncAdapter 的文档有一个关于取消的部分:

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.