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

前端之家收集整理的这篇文章主要介绍了android – 使用addPeriodicSync时,停止同步适配器最初同步前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的项目中使用同步适配器,它将定期同步.要为同步适配器创建帐户,我使用以下代码.

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

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

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

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

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

  1. Account account = new Account(context.getPackageName(),context.getPackageName());
  2.  
  3. AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
  4.  
  5. if (accountManager.addAccountExplicitly(account,null,null)) {
  6.  
  7. // Inform the system that this account supports sync
  8. ContentResolver.setIsSyncable(account,context.getPackageName(),1);
  9.  
  10. // Inform the system that this account is eligible for auto sync when the network is up
  11. ContentResolver.setSyncAutomatically(account,true);
  12.  
  13. // Recommend a schedule for automatic synchronization.
  14. // The system may modify this based
  15. // on other scheduled syncs and network utilization.
  16. ContentResolver.addPeriodicSync(account,Bundle.EMPTY,AppConstants.SYNC_INTERVAL);
  17. }

解决方法

您可以在第一次手动同步后安排未来事件.
  1. private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  2.  
  3. private void setDelayedAutoSync() {
  4. ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
  5. @Override
  6. public void run() {
  7. Log.d(TAG,"Out of time!");
  8. ContentResolver.setSyncAutomatically(account,content_authority,true);
  9. ContentResolver.addPeriodicSync(account,new Bundle(),SYNC_FREQUENCY_CONSTANT);
  10. },SYNC_FREQUENCY_CONSTANT,TimeUnit.SECONDS);
  11. }

猜你在找的Android相关文章