I just created an Account for my app.
I also followed all the steps from here: https://stackoverflow.com/a/5255360/327402
This is my code to get the sync by code
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType(ACCOUNT);
//Log.e("DEBUG", "Accounts: " + accounts.length);
if (accounts.length == 0) {
Account account = new Account(getString(R.string.app_name), ACCOUNT);
ContentResolver.setIsSyncable(account, AUTHORITY, 1);
ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), 7200);
ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
if (am.addAccountExplicitly(account, "pass1", null))
Log.i("DEBUG", "account Created: " + account.name + ", " + account.type);
else
Log.i("DEBUG", "addAccountExplicitly returned false");
}
else{
ContentResolver.requestSync(accounts[0], AUTHORITY, new Bundle());// THIS IS WORKING!!!
}
}
So, everything looks correct and fine.
But unfortunately, I cannot get a periodic sync! When I open the settings, accounts, I see the account and the date and time is the time when I performed the sync by code, or manually.
Any idea on what I did wrong, or what I forgot?
Rewrite
I have put together a sample project on GitHub that demonstrates a working SyncAdapter. The project is here.
I have only tried this on an emulator with API 17 since I didn't want to wait around an hour or so (maybe longer now) for a sync to happen. I would suggest that you take this route as well.
On API 17, this demo will do a sync every 30 seconds or so. Everything runs out of the main activity with stub support classes: SyncAdapter, StubProvider, etc. The only thing the sync adapter does is to log a message to logcat that it has run.
I don't really see anything wrong with your code other than, perhaps, the order of the calls to set up the sync is incorrect. Take a look at the call order in the demo for an example of what works.
I hope you find this useful.
(I did this on Android Studio 3.0 Canary 5. I hope this is not an issue.)
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