使用addPeriodicSync时,停止同步适配器最初同步

zap*_*.10 8 android android-contentresolver android-syncadapter

我在我的项目中使用同步适配器,它将定期同步.要为同步适配器创建帐户,我使用以下代码.

我面临的问题是此代码触发了初始同步.文档中没有提到此代码将使同步最初运行.

事实上即使在谷歌示例项目中也有额外的代码用于触发我已删除的初始同步.

我使用了此示例中的代码:http: //developer.android.com/samples/BasicSyncAdapter/index.html

即使我添加命令ContentResolver.cancelSync(account,null); 同步适配器仍然运行.

如何阻止同步适配器最初同步.它应该在同步间隔周期过去后第一次同步.

Account account = new Account(context.getPackageName(), context.getPackageName());

AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

if (accountManager.addAccountExplicitly(account, null, null)) {

        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, context.getPackageName(), 1);

        // Inform the system that this account is eligible for auto sync when the network is up
        ContentResolver.setSyncAutomatically(account, context.getPackageName(), true);

        // Recommend a schedule for automatic synchronization. 
        // The system may modify this based
        // on other scheduled syncs and network utilization.
        ContentResolver.addPeriodicSync(account, context.getPackageName(),
                Bundle.EMPTY, AppConstants.SYNC_INTERVAL);
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 0

您可以在第一次手动同步后安排未来的事件。

private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

private void setDelayedAutoSync() {
            ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "Out of time!");
                ContentResolver.setSyncAutomatically(account, content_authority, true);
                ContentResolver.addPeriodicSync(account, content_authority, new Bundle(),SYNC_FREQUENCY_CONSTANT);
        }, SYNC_FREQUENCY_CONSTANT, TimeUnit.SECONDS);
    }
Run Code Online (Sandbox Code Playgroud)