JamesNWarner JamesNWarner - 1 year ago 236
Java Question

Android - Enable automatic sync when sync adapter is setup

I am writing an application which uses a sync adapter to synchronize data.

I've read up on the documentation and I'm pretty sure I understand how it all works. I've got most of my sync adapter working by following this great guide written by Udi Cohen.

However I do have one issue which I can't seem to solve, and thats enabling sync automatically when my app is installed.

When my app runs up, it creates a sync adapter and an account, does all the work you would expect it to do, which is great. However, if I go to Settings > Accounts > 'My App', the sync is off. Is there anyway I can get this to be automatically enabled?

Screenshot of Accounts > 'My App'

When setting up the sync adapter my code looks like this:

// Inform the system that this account supports sync
ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);

// Inform the system that this account is eligible for auto sync
ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);

// Recommend a schedule for auto sync
ContentResolver.addPeriodicSync(account, CONTENT_AUTHORITY, new Bundle(), SYNC_FREQUENCY);

newAccount = true;

From reading up around sync adapters, I believed that
was the right method to use to enable sync automatically.

I have also tried setting
but that doesn't seem to have any effect.

I have the permission
declared in my AndroidManifest so that's not the problem. I also have the sync service and xml file in my project too. I have attached the code for these below.

Has anyone else had a similar issue? Could it be a permissions problem?
If anyone has any suggestions I would be happy to try them. Thanks.


<action android:name="android.content.SyncAdapter"/>


<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"

Answer Source

I eventually found out what was causing my issue.

In my syncadapter.xml I had my content authority set to android:contentAuthority="com.android.calendar".

However, in my code where I was setting the sync to automatic using ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true); my content authority value was actually set to something different from my content autheority in the XML.

The content authority when setting up your sync adapter must match the content authority used in the XML.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download