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

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

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.

This Post Has 71 Comments

  1. Hah, I love that not catching an exception reboots the device 🙂 Thanks for this Sam. Very interesting.

  2. How are you starting the AccountAuthenticatorService service? I’ve not been able to figure this out in your code so far. Thanks.

    1. The Android system automatically starts the service when the user adds an account from the Accounts & Sync settings screen.

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

  4. Try using addAccountExplicitly() instead of addAccount() as I do in my sample implementation above

  5. 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;
    }

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

  7. Yes. But I’m guessing its got something to with my not using the correct context to call the service from.

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

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

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

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

  12. @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?

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

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

  15. @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…

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

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

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

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

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

  21. @popopome
    OOPS.

    <intent-filter>
    <action android:name=”android.intent.action.MAIN” />
    <category android:name=”android.intent.category.DEFAULT” />
    </intent-filter>

  22. Hi,
    in my previuos post, came to know we cant use AccountManagerService. Therefore using account manager.
    i need help to delete accounts which are displayed in “account and sync” from my app.

    i’m trying with this code:
    AccountManager accountManager = (AccountManager)mContext.getSystemService(Context.ACCOUNT_SERVICE);
    android.accounts.Account[] accounts = AccountManager.get(mContext).getAccounts();
    for (android.accounts.Account account: accounts) {
    AccountManager.get(mContext).removeAccount(account, null, null);
    }

    but i’m getting accounts = 0 i.e. no accounts. whereas accounts exist.
    It would be great help if u can suggest something to resolve my problem.

  23. If you get the UID doesn’t match error, check the AUTH_TOKEN you set in the app vs the one you have in your account-authenticator xml file, they need to match.

  24. I got a problem.
    The relevant part of my account_preferences.xml looks like this:
    […]

    […]

    The Activity-definition in the main-manifest looks like this:
    […]

    […]

    When I click on the Preference-Screen defined above then this activity should be started, but everytime I do so the whole process crashes and logcat says:

    09-15 16:38:57.191: ERROR/AndroidRuntime(30057): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

    Where is my mistake?

    David

  25. Oh sorry:
    account_preferences:

    and manifest:

  26. Anyone know what is the importance of account type?

    I tried to change the “accountType” field in xml

    android:accountType=”org.c99.SyncProviderDemo.account”.

    It seams like any name will do (e.g: abc.account , cde.abc.google, etc) as long as I change the same field in “sync_contacts.xml” and “authenticator.xml”. However, only “com.google” would result in UID error.

    anyone knows what happen?

  27. @Sean that field is what uniquely identifies your specific account type. You should choose an identifier that’s unique to your application.

  28. @Sam Steele
    I can’t create account with “com.google” account type. Any ideas ?

  29. @Sean com.google belongs to Google. Use a different domain.

  30. Hi:
    I also encountered the alike error message, “W/AccountManagerService( 52): caller uid 10026 is different than the authenticator’s uid”.
    And I replaced the substring “org.c99” in “org.c99.SyncProviderDemo” as the path of my project. Then everything is ok.

    Thank you all for sharing what you know, it helps me a lot!! : )

  31. @Hi
    Hi:
    I also encountered the alike error message, “W/AccountManagerService( 52): caller uid 10026 is different than the authenticator’s uid”.
    And I replaced the substring “org.c99” in “org.c99.SyncProviderDemo” as the path of my project. Then everything is ok.

    Thank you all for sharing what you know, it helps me a lot!! : )

  32. Hi Sam
    I have couple of questions
    1) Can we use syncAdapter to get data of a row of raw_contact table if that row has been affected (i.e added/deleted/edited). I know ContentObserver notify whenever raw_content table changes in onChange() method but we dont know which row has been changed ( to put this in another way if we add how would we know and if deleted we still get it through deleted flag in raw_contact table but how about edited one??).

    2) when we get notification in ContentObserver can we fire requestSync (Account account, String authority, Bundle extras) to start Sync ?? how we can get data of raw_contact affected by contact application using these to parameters .

    thanks again man !! your blog is really nice please share some idea what you think

  33. himanshu :
    Hi Sam
    I have couple of questions
    1) Can we use syncAdapter to get data of a row of raw_contact table if that row has been affected (i.e added/deleted/edited). I know ContentObserver notify whenever raw_content table changes in onChange() method but we dont know which row has been changed ( to put this in another way if we add how would we know and if deleted we still get it through deleted flag in raw_contact table but how about edited one??).
    2) when we get notification in ContentObserver can we fire requestSync (Account account, String authority, Bundle extras) to start Sync ?? how we can get data of raw_contact affected by contact application using these to parameters .
    thanks again man !! your blog is really nice please share some idea what you think

  34. Hi,

    I found the same error as @David’s.
    Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

    Can anyone help to solve the issue?

  35. Sam Steele, I’m even can’t even express in words how grateful to you! This topic is very difficult, and no one explain everythih so clear as you! THANKS.

  36. how to turn auto sycn on ?

  37. I meant programmatically

    sendi :
    how to turn auto sycn on ?

  38. You have a typo in your activity excerpt:

    Bundle extras = getIntent.getExtras();

    should be…

    Bundle extras = getIntent().getExtras();

    Thanks for the great tutorial!

    Cheers!

  39. hii…..
    i need the use of account manager for adding a new account…Can u please tell me how to use your code because its showing error in the xmls tht “error: Error: No resource found that matches the given name (at ‘resource’ with value ‘@xml/authenticator’).”

Comments are closed.

Close Menu