Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyncAdapter: Account created, requestSync OK, but setSyncAutomatically not Working

I just created an Account for my app.

  • The account is visible in settings
  • I set syncable="true" in my XML
  • I can perform a manual sync by pressing the settings -> onPerformSync is called
  • I can perform a "code" sync by calling ContentResolver.requestSync -> onPerformSync is called
  • And of course, yes, the sync is enabled in settings. I don't use any power saver.

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?

like image 413
Waza_Be Avatar asked May 22 '17 14:05

Waza_Be


1 Answers

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.)

like image 56
Cheticamp Avatar answered Jan 04 '23 04:01

Cheticamp