Can some one help me with step by step approach to use the AccountManager in android along with a minimalistic example for better understanding?
Asked
Active
Viewed 3,771 times
1 Answers
7
I'm actually answering this so I can get a clear understanding myself, so here goes (I'm by no means proficient with Android yet):
An application will usually want to check for the existence of an account first, you can use:
AccountManager mgr = AccountManager.get(getApplicationContext());
Account[] accounts = mgr.getAccountsByType("com.mydomain");
// assert that accounts is not empty
You'll want to use an AccountManagerFuture<Bundle>
to hold results of the authentication token. This has to be async since the Android device may ask the user to login in the meantime:
private AccountManagerFuture<Bundle> myFuture = null;
private AccountManagerCallback<Bundle> myCallback = new AccountManagerCallback<Bundle>() {
@Override public void run(final AccountManagerFuture<Bundle> arg0) {
try {
myFuture.getResult().get(AccountManager.KEY_AUTHTOKEN); // this is your auth token
} catch (Exception e) {
// handle error
}
}
}
Now you can ask for the auth token asynchronously:
myFuture = mgr.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, true, myCallback, null);
AUTH_TOKEN_TYPE
is dependent on your authentication mechanism. For google accounts it is simply 'ah'.
Now whenever you do an authenticated request just pass along the token (in the header, as a param, etc), so the server side knows who you are.

Abdullah Jibaly
- 53,220
- 42
- 124
- 197
-
1Here's a more comprehensive guide: http://udinic.wordpress.com/2013/04/24/write-your-own-android-authenticator – Udinic Apr 25 '13 at 15:41