Search code examples
androidauthenticationaccountmanager

How to store and retrieve auth_token to/from AccountManager


I am using AccountManager for storing auth_token. I am using the following code to store the auth_token. But I am not able to retrieve it back.

AccountManager.get(this).addAccountExplicitly(account, "", bundle);

And, I am using following code (using Volley library) to retrieve it back, but it's throwing AuthFailureError.

try {
    Logging.d(LOG_TAG, "AUTH TOKEN : "
            + (new AndroidAuthenticator(this, account,
                    CustomAuthenticator.AUTHTOKEN_TYPE).getAuthToken()));
} catch (AuthFailureError e) {
    Logging.d(LOG_TAG, "AUTH FAILURE");
    e.printStackTrace();
}

Any suggestions ?


Solution

  • Finally, I could able to retrieve the auth_token through this snippet:

    final AccountManagerFuture<Bundle> future = AccountManager.get(this)
            .getAuthToken(account, authTokenType, null, this, null, null);
    
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Bundle bnd = future.getResult();
                final String authtoken = bnd
                        .getString(AccountManager.KEY_AUTHTOKEN);
                Logging.d(LOG_TAG, (authtoken != null) ? "SUCCESS!\ntoken: "
                        + authtoken : "FAIL");
            } catch (Exception e) {
                e.printStackTrace();                }
        }
    }).start();