Writing an Android Sync Provider: Part 1
One of the highlights of the Android 2.0 SDK is that you can write custom sync providers to integrate with the system contacts, calendars, etc. The only problem is that there’s very little documentation on how it all fits together. And worse, if you mess up in certain places, the Android system will crash and reboot! Always up for a challenge, I’ve navigated through the sparse documentation, vague mailing list posts, and the Android source code itself to build a sync provider for our Last.fm app. Want to know how to build your own? Read on!
Account Authenticators
The first piece of the puzzle is called an Account Authenticator, which defines how the user’s account will appear in the “Accounts & Sync” settings. Implementing an Account Authenticator requires 3 pieces: a service that returns a subclass of AbstractAccountAuthenticator from the onBind method, an activity to prompt the user to enter their credentials, and an xml file describing how your account should look when displayed to the user. You’ll also need to add the android.permission.AUTHENTICATE_ACCOUNTS permission to your AndroidManifest.xml.
The Service
The authenticator service is expected to return a subclass of AbstractAccountAuthenticator from the onBind method — if you don’t, Android will crash and reboot when you try to add a new account to the system. The only method in AbstractAccountAuthenticator we really need to implement is addAccount, which returns an Intent that the system will use to display the login dialog to the user. The implementation below will launch our app’s main launcher activity with an action of “fm.last.android.sync.LOGIN” and an extra containing the AccountAuthenticatorResponse object we use to pass data back to the system after the user has logged in.
AccountAuthenticatorService.java
-
import fm.last.android.LastFm;
-
import android.accounts.AbstractAccountAuthenticator;
-
import android.accounts.Account;
-
import android.accounts.AccountAuthenticatorResponse;
-
import android.accounts.AccountManager;
-
import android.accounts.NetworkErrorException;
-
import android.app.Service;
-
import android.content.Context;
-
import android.content.Intent;
-
import android.os.Bundle;
-
import android.os.IBinder;
-
import android.util.Log;
-
-
/**
-
* Authenticator service that returns a subclass of AbstractAccountAuthenticator in onBind()
-
*/
-
public class AccountAuthenticatorService extends Service {
-
private static final String TAG = "AccountAuthenticatorService";
-
private static AccountAuthenticatorImpl sAccountAuthenticator = null;
-
-
public AccountAuthenticatorService() {
-
super();
-
}
-
-
public IBinder onBind(Intent intent) {
-
IBinder ret = null;
-
if (intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT))
-
ret = getAuthenticator().getIBinder();
-
return ret;
-
}
-
-
private AccountAuthenticatorImpl getAuthenticator() {
-
if (sAccountAuthenticator == null)
-
sAccountAuthenticator = new AccountAuthenticatorImpl(this);
-
return sAccountAuthenticator;
-
}
-
-
private static class AccountAuthenticatorImpl extends AbstractAccountAuthenticator {
-
private Context mContext;
-
-
public AccountAuthenticatorImpl(Context context) {
-
super(context);
-
mContext = context;
-
}
-
-
/*
-
* The user has requested to add a new account to the system. We return an intent that will launch our login screen if the user has not logged in yet,
-
* otherwise our activity will just pass the user's credentials on to the account manager.
-
*/
-
@Override
-
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options)
-
throws NetworkErrorException {
-
Bundle reply = new Bundle();
-
-
Intent i = new Intent(mContext, LastFm.class);
-
i.setAction("fm.last.android.sync.LOGIN");
-
i.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
-
reply.putParcelable(AccountManager.KEY_INTENT, i);
-
-
return reply;
-
}
-
-
@Override
-
public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) {
-
return null;
-
}
-
-
@Override
-
public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
-
return null;
-
}
-
-
@Override
-
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
-
return null;
-
}
-
-
@Override
-
public String getAuthTokenLabel(String authTokenType) {
-
return null;
-
}
-
-
@Override
-
public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException {
-
return null;
-
}
-
-
@Override
-
public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) {
-
return null;
-
}
-
}
-
}
The account authenticator service should be defined in your AndroidManifest.xml, with a meta-data tag referencing an xml definition file, as follows:
Snippet from AndroidManifest.xml
-
<service android:name="AccountAuthenticatorService"
-
android:exported="true" android:process=":auth">
-
<intent-filter>
-
<action android:name="android.accounts.AccountAuthenticator" />
-
</intent-filter>
-
<meta-data android:name="android.accounts.AccountAuthenticator"
-
android:resource="@xml/authenticator" />
-
</service>
The Activity
If you don’t already have a login screen, there’s a convenience class AccountAuthenticatorActivity you can subclass that will pass your response back to the authentication manager for you, however if you already have a login activity in place you may find it easier to just pass the data back yourself, as I have done here. When the user has successfully been authenticated, we create an Account object for the user’s credentials. An account has an account name, such as the username or email address, and an account type, which you will define in your xml file next. You may find it easier to store your account type in strings.xml and use getString() to fetch it, as it is used in multiple places.
Snippet from the Last.fm login activity
-
Account account = new Account(username, getString(R.string.ACCOUNT_TYPE)));
-
AccountManager am = AccountManager.get(this);
-
boolean accountCreated = am.addAccountExplicitly(account, password, null);
-
-
Bundle extras = getIntent.getExtras();
-
if (extras != null) {
-
if (accountCreated) { //Pass the new account back to the account manager
-
AccountAuthenticatorResponse response = extras.getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
-
Bundle result = new Bundle();
-
result.putString(AccountManager.KEY_ACCOUNT_NAME, username);
-
result.putString(AccountManager.KEY_ACCOUNT_TYPE, getString(R.string.ACCOUNT_TYPE));
-
response.onResult(result);
-
}
-
finish();
-
}
The XML definition file
The account xml file defines what the user will see when they’re interacting with your account. It contains a user-readable name, the system account type you’re defining, various icons, and a reference to an xml file containing PreferenceScreens the user will see when modifying your account.
authenticator.xml
-
<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
-
android:accountType="fm.last.android.account"
-
android:icon="@drawable/icon"
-
android:smallIcon="@drawable/icon"
-
android:label="@string/app_name"
-
android:accountPreferences="@xml/account_preferences"/>
account_preferences.xml
-
<PreferenceScreen
-
xmlns:android="http://schemas.android.com/apk/res/android">
-
<PreferenceCategory
-
android:title="General Settings" />
-
-
<PreferenceScreen
-
android:key="account_settings"
-
android:title="Account Settings"
-
android:summary="Sync frequency, notifications, etc.">
-
<intent
-
android:action="fm.last.android.activity.Preferences.ACCOUNT_SETUP"
-
android:targetPackage="fm.last.android"
-
android:targetClass="fm.last.android.activity.Preferences" />
-
</PreferenceScreen>
-
</PreferenceScreen>
Putting it all together
Now we’re ready for testing! The Android accounts setting screen doesn’t handle exceptions very well — if something goes wrong, your device will reboot! A better way to test is to launch the emulator, run the “Dev Tools” app, and pick “AccountsTester”.

You should see your new account type in the list, along with the built-in “Corporate” account type. Go ahead and select your account type from the drop-down list, and then press the “Add” button, and you should be presented with your login activity. After authenticating, your account should appear in a list below the buttons. At this point, it should be safe to use the system “Accounts & Sync” settings screen to remove or modify your account.

Ready to fill in that section below “Data & synchronization”? Let’s move on to part 2!
The source code for the implementation referenced here is available in my Last.fm github project under the terms of the GNU General Public License. A standalone sample project is also available here under the terms of the Apache License 2.0. Google has also released their own sample sync provider on the Android developer portal that’s a bit more complete than mine.












Hah, I love that not catching an exception reboots the device
Thanks for this Sam. Very interesting.
How are you starting the AccountAuthenticatorService service? I’ve not been able to figure this out in your code so far. Thanks.
The Android system automatically starts the service when the user adds an account from the Accounts & Sync settings screen.
I’m facing a problem with adding an account since the past few days.
My addAccount implementation in AccountAuthenticatorService looks like the below:
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Bundle result;
result = addAccount(mContext, “user”, “session_key”);
return result;
}
The logcat output looks like the below:
V/AddAccount( 53): Attempting to add account of type com.android.apps.myapp.account
W/AccountManagerService( 53): caller uid 10044 is different than the authenticator’s uid.
After this, nothing happens and I don’t see my account in the list under “Accounts & Sync”. Any idea why this could be happening? Do I have to give it a real user name and session key? Also what’s up with the caller UID warning? Any input would be appreciated. Thanks.
Try using addAccountExplicitly() instead of addAccount() as I do in my sample implementation above
Well, I was using it from my addAccount function. Still I changed AbstractAccountAuthenticator.addAccount() it to the below to use addAccountExplicitly(). Still no luck though, getting the same message on logcat.
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Bundle result = null;
Account account = new Account(“username”, AccAuthSvc.this.getString(R.string.ACCOUNT_TYPE));
AccountManager am = AccountManager.get(AccAuthSvc.this);
if (am.addAccountExplicitly(account, null, null)) {
result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
}
return result;
}
Did you set your service to run as a separate process in the AndroidManifest.xml? android:exported=”true” android:process=”:auth” are the magic flags
Yes. But I’m guessing its got something to with my not using the correct context to call the service from.
Thanks for the code and explanation.
However, when I click on Add Account in “Accounts & Sync” it takes me to the default Exchange screen. My service isnt getting fired at all. I don’t see Account Authenticator intent being raised either.
I’ve posted a standalone sync provider demo project to GitHub that should make it easier to understand: http://github.com/c99koder/AndroidSyncProviderDemo
@Hmm if your account doesn’t appear in the Accounts & Sync add screen, then you haven’t defined it properly in the various xml files, including your android manifest.
Thanks very much for a great post.
One question. I’ve installed the AndroidSyncProviderDemo in the emulator and configured the account “efudd” now shows up on my “Account and sync Settings” settings page.
However, I was expecting that when I create a new contact that it would either default to the new sync provider or prompt me for a choice.
sqlite> select _id, account_name, account_type, display_name from raw_contacts;
select _id, account_name, account_type, display_name from raw_contacts;
_id|account_name|account_type|display_name
1|efudd|org.c99.SyncProviderDemo.account|Elmer Fudd
2|||Test1
3|||Test2
4|||Test3
How can I make efudd|org.c99.SyncProviderDemo.account the account for all new contacts?
Thanks again
Discovered the answer:
- the AndroidSyncProviderDemo ships with android:supportsUploading=”false” in sync_contacts.xml
- set it to android:supportsUploading=”true” and re-install the app
Then all contacts created will be assigned to the demo provider
@Hi
Having the same problem here; anyone know what causes it? Everything works fine up until the login is complete and the authenticator response is sent, and that’s when it crashes with:
W/AccountManagerService( 52): caller uid 10026 is different than the authenticator’s uid
E/AndroidRuntime( 348): java.lang.SecurityException: caller uid 10026 is different than the authenticator’s uid
E/AndroidRuntime( 348): at android.os.Parcel.readException(Parcel.java:1218)
E/AndroidRuntime( 348): at android.os.Parcel.readException(Parcel.java:1206)
E/AndroidRuntime( 348): at android.accounts.IAccountManager$Stub$Proxy.addAccount(IAccountManager.java:506)
E/AndroidRuntime( 348): at android.accounts.AccountManager.addAccountExplicitly(AccountManager.java:246)
android:proc=”:auth” is set in AndroidManifest (and can be seen in logcat when the service starts up). What could be causing this?
That usually means that you are passing in the wrong context when you’re calling AccountManager.get(this).addAccountExplicitly. You need to make sure that you’re using the same context every time you call AccountManaget.get(). This is to prevent other things from messing with accounts your service has created.
@Berto
I’ve apparently done something to break it even more, since then — now it doesn’t even launch my Login activity. Gets up to the return value of onBind(), after instantiating the AccountAuthenticatorImpl, then appears to do nothing with that IBinder. Doesn’t call AccountAuthenticatorImpl.addAccount(), which is what returns the Login activity’s Intent.
@Joe
You may want to look at the code here: http://developer.android.com/resources/samples/SampleSyncAdapter/index.html
It appears as though Google has finally put up a fully-coded and working sample.
@Berto
Fully-coded is a bit “strong” – it’s read-only for the simple reason that they’ve intentionally broken contacts sync so badly that only google contacts sync and their own exchange sync works properly with the default contacts app…
Great job!
One question about the account management on Android. Now that we can add facebook account to the platform, is it possible to share the account across multiple facebook clients in the platform? I can login once, and update my facebook status in several applications if necessary. how to do that?
thanks a lot!
Facebook would need to implement that in their account provider. We’ve implemented third party authentication in the Last.fm app, and I’ve written a demo app to show how you can authenticate with the user’s existing Last.fm account here: http://github.com/c99koder/lastfm-android/tree/master/LastFmAuthTest/
Hi,
Can I ask when will the override function onbind be called? I have my own code, but it cannot be called unless I use context.startService or context.bindService. Thanks!!
@Joe
If you get the “java.lang.SecurityException: caller uid” message, check your XML for
android:accountType=”org.c99.SyncProviderDemo.account”.
make sure the packagename is correct, especially if you rename the package and use all lowercase, the XML should also have all lowercase. At least that was what tripped me.
It may be wrong place to log my query, but its urgent.
can anyone please help me how to delete google account from “accounts and sync”.
I’m trying to call this line my app:
AccountManagerService.getSingleton().onServiceChanged(null,true);
whereas onServiceChanged() method is defined in AccountManagerService.java.
this piece of code is not doing anything i feel exception is bieng thrown which is handled at lower layer.
Please help if anyone is aware how to call this function or how to delete account.
@Joe
Hey joe.
I had same problems but when I added for the activity the problem is solved.
Google’s sample does not define in manifest file
I doubt whether their sample works for my emulator.
@popopome
OOPS.
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>