How to retrieve an Facebook-AuthToken from the accounts saved on Android

Dennis Winter picture Dennis Winter · Jan 4, 2011 · Viewed 9.4k times · Source

I'm trying to retrieve the AuthToken for Facebook (saved by Facebook for Android) by using the following piece of code.

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.facebook.auth.login");
if (accounts.length > 0) {          
    for(int j = 0; j < accounts.length; j++) {
        Account account = accounts[j];
        if(account.type != null && account.type.equals("com.facebook.auth.login")) { 
            Log.e(RuntimeVars.MY_NAME, "FACEBOOK-TYPE FOUND");
            am.getAuthToken(account, "com.facebook.auth.login", null, ConversationList.this,
                new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> arg0) {
                        try {
                            Bundle b = arg0.getResult();
                            Log.e(RuntimeVars.MY_NAME, "THIS AUTHTOKEN: " + b.getString(AccountManager.KEY_AUTHTOKEN));
                        }
                        catch (Exception e) {
                            Log.e(RuntimeVars.MY_NAME, "EXCEPTION@AUTHTOKEN");
                        }
                    }
                }, null);
            }
        }
    }

The login credentials are found and FACEBOOK-TYPE FOUND is written into LogCat, but neither THIS AUTHTOKEN: [...] nor EXCEPTION@AUTHTOKEN is logged. So I suppose am.getAuthToken is never called.

What am I missing?

In general, if there is a better (and at least working) approach to retrieve the Facebook authtoken from the Android accounts please let me know.

Thanks a lot for your help!

Best regards
S.

Answer

Olle picture Olle · Jan 10, 2011

Why not use the Facebook SDK?

The Facebook class in it has a member to get the OAuth 2.0 access token (if that is what you need), getAccessToken().