Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AccountManager.getAuthToken returns empty string, sometimes

Tags:

android

I've got an odd behaviour when using Android's AccountManager to get an auth token for a Google account.

When the app launches, the first call to getAuthToken returns a bundle with an empty string as token. The next time, I call the very same method, it returns a valid token.

Here's my code:

public String updateToken(final boolean invalidateToken, final Context c) {
    String authToken = "";
    try {
        final AccountManager am = AccountManager.get(c);
        final Account[] accounts = am.getAccountsByType("com.google");

        final Bundle bundle = am.getAuthToken(accounts[0], "android", true,
                null, null).getResult();

        authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN)
                .toString();

        if (invalidateToken) {
            am.invalidateAuthToken("com.google", authToken);
            authToken = updateToken(false, c);
        }
    } catch (final Exception e) {
        //Just for debugging issues.
        e.printStackTrace();
    }
    return authToken;
}

It looks like the empty token is returned, when this method is called in the onCreate method of my activity, although it's not always the case.

Thanks in advance. Also I don't really know when to invalidate the token. Once a day? On every start up? Or is the empty token the indicator, that the token has to be invalidated, although it returns a valid token on the very next call.

like image 550
Kirill Rakhman Avatar asked Feb 08 '12 12:02

Kirill Rakhman


1 Answers

You need to invalidate the token before requesting one.

See AuthToken from AccountManager in Android Client No Longer Working

like image 53
shkschneider Avatar answered Sep 24 '22 00:09

shkschneider