【问题标题】:Stop sync adapter to sync initially when using addPeriodicSync使用 addPeriodicSync 时停止同步适配器以进行初始同步
【发布时间】:2017-09-29 15:05:52
【问题描述】:

我在我的项目中使用了一个同步适配器,它会定期同步。要为同步适配器创建帐户,我使用以下代码。

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

事实上,即使在 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);
}

【问题讨论】:

    标签: android android-contentresolver android-syncadapter


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以在首次手动同步后安排未来的活动。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多