Skip to content Skip to sidebar Skip to footer

Android Accountmanager

Can some one help me with step by step approach to use the AccountManager in android along with a minimalistic example for better understanding?

Solution 1:

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 = newAccountManagerCallback<Bundle>() {
    @Overridepublicvoidrun(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.

Post a Comment for "Android Accountmanager"