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 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 “” and an extra containing the AccountAuthenticatorResponse object we use to pass data back to the system after the user has logged in.

import; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import; 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(""); 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

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



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

This Post Has 71 Comments

  1. hanan

    i’m a student and this is my first year in collage.
    i got a homework from my java lecture about webservice.
    he ask every students find an android applications that implemented webservice.
    then i choose your apps, srobbler last FM.
    but, really confused how they work.
    he asking everyone of us to explain it clearly.

    i wanna asking bout,
    1. how your apps can shown wiki artist?
    2. are you stored all the info bout artist on a database?
    3. how can i describe the process?

    i read in many websites, they talkin bout soap, WSDL, XML,etc. but still didnt get it.
    then, i moved to forum, but still didn’t get the reply.
    I really hope u can help me.

    ~ regards Hanan

    * sorry for my bad english (using google translate)

  2. Zhemin Yin

    Thanks for great sample.
    I have some question on Android built-in sync.
    Can i fire onPerformSync() method when i click a button in a app?
    How can i set period of sync?
    What is requestSync() method?
    I hope you help me.

  3. GENiAli

    thx for this post.

  4. rinpc


  5. narayan soni


    i used your code in my apps the account add successfully but when i open setting the force close error occur and if i run your code its work fine

  6. Ken Lim

    Hi I read you blog and I do not understand how to add you code to my login page…where do I put it? This is the code for my login page…..any help will be appreciated

    public class MainActivity extends Activity {

    String userName, passWord;
    EditText username, password;
    Button login, forgotPassword;

    public void onCreate(Bundle savedInstanceState) {
    // this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    username = (EditText) findViewById(;
    password = (EditText) findViewById(;

    login = (Button) findViewById(;

    private OnClickListener loginListener = new OnClickListener() {
    public void onClick(View v) {
    // if (username.getText().toString().equals(“u”)
    // && password.getText().toString().equals(“pw”)) {
    Intent i = new Intent(MainActivity.this, EventList.class);
    // }

    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(, menu);
    return true;

  7. Javier

    I have an error when calling addAccountExplicitly.. in my activity..error says “caller uid 10075 is different than the authentication uid”..

    I am sure that my authenticator.xml account type is the same than activity`s account object.

    I am not sure of my manidest declared service.. here
    <service android:name="AccountAuthenticatorService"… is this name come from package.serviceClass? I have seen more examples where put ".authenticator.serviceClass"

    Any ideas about all this?
    Thanks in advance

  8. vineet

    you are doing good work.
    For using your tutorial, i have create account and show contact sync menu in Account & Sync.
    I don’t understand, how to sync with own server. where we place code for contact sync?
    Please reply me, i am waiting for your response.

    Thanks in advance

  9. nikmin

    Hi is there a way to do contacts synchronization without using a token at all? I want to send username and password only. I see that it is less secure, but is there a way to do it and how to do it? I searched but I couldn’t finds any example without using a token.

  10. Ankit

    Hi can u tell me what is the username & password for this. If i have to create an account the how can create that account

  11. Angel

    I did exactly what you said. But I am not getting anything when I tap on Add button in Account Tester.

  12. Angel

    You have written this line
    do we need to change it to our package?

  13. Thiago

    I need to sync contacts from all accounts. Is it possible?

  14. Rajesh

    Could you clarify following douts

    1. Which is Best Approach to development Email Synch Client( Exchange or Lotus Domino) is it token based or Push Method or is there any other method?.

    2. Which would be consume less battery?.

  15. Dheeraj Kumar saini

    I am using this code. But giving error.

    05-10 15:53:53.313: E/AndroidRuntime(16472): java.lang.RuntimeException: Unable to get provider service.CallLogSyncAdapter:
    java.lang.InstantiationException: can’t instantiate class service.CallLogSyncAdapter; no empty constructor

    After giving this error. my phone is hanged and now is not restarting. Can you help me.

  16. Shaiju MS

    Is there any way toDisplay the app icons if the contact is associated with other application in phone address book

  17. Deepak Kishore

    How to sync my existing contacts with the app

  18. Bayron

    This solution is not working on Android devices and the Samsung or the Android Lollipop. Do you have any idea what might be happening?

Comments are closed.