繁体   English   中英

使用addPeriodicSync时停止同步适配器以进行初始同步

[英]Stop sync adapter to sync initially when using addPeriodicSync

我在项目中使用了同步适配器,该适配器会定期同步。 要创建同步适配器帐户,请使用以下代码。

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

实际上,即使在google示例项目中,也有触发我已删除的初始同步的额外代码。

我使用了此示例中的代码: 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);
}

初始同步是显式添加帐户的结果。

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

每当添加/删除触发同步的帐户时,同步适配器都会发送广播。 请参考SyncManager源类。

可以通过在传递给onPerformSync()的Bundle中添加特定密钥并检查该密钥以触发同步,而不发送空捆绑来避免这种情况。

    Bundle bundle = new Bundle();
    bundle.putBoolean("MySync", true);
    ContentResolver.addPeriodicSync(account, context.getPackageName(),
            bundle, AppConstants.SYNC_INTERVAL);
    ....


    onPerformSync(...) {
      if(bundle.containsKey("MySync")) {
        //perform your sync
      }
    }

您可以在首次手动同步后安排将来的事件。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM