Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop sync adapter to sync initially when using addPeriodicSync

I am using a sync adapter in my project which will sync periodically. To create the account for sync adapter I am using the below code.

The issue I am facing is that this code is triggering an initial sync. The documentation has no where mentioned that this code will make the sync to run initially.

In fact even in the google sample project there is extra code for triggering an initial sync which I have removed.

I have used the code from this sample: http://developer.android.com/samples/BasicSyncAdapter/index.html

Even if I add command ContentResolver.cancelSync(account, null); the sync adapter still runs.

How can I stop the sync adapter from syncing initially. It should sync for the first time when the sync interval period has passed.

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);
}
like image 301
zaphod100.10 Avatar asked May 30 '15 17:05

zaphod100.10


1 Answers

The initial sync happens as a result of adding an account explicitly.

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

There is a broadcast sent by Sync Adapter whenever there is addition/deletion of an account which triggers the sync. Please refer the SyncManager source class.

It can be avoided by adding a specific key in Bundle passed to onPerformSync() and check for the same to trigger the sync instead of sending an empty 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
      }
    }
like image 178
Harini S Avatar answered Oct 26 '22 17:10

Harini S