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);
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With