Toxic Bakery

Archive for July, 2010

Getting Google Auth Sub Tokens In Your Android Applications

by on Jul.23, 2010, under Android Development

Picture of the Android logo

Android Logo

For an app that I am working on I initially was going to ask the user for a username and password for their Google account and login with that information. However once I actually thought about how I would take a question like that, I quickly decided against that method. Instead I decided to look into what it would take to get a Google auth token to use as a login method to different services. Unfortunately this can only be done with Android 2.1 or greater however most phones should be on 2.1 here shortly so that hopefully won’t be a deal breaker for you.

Anyways, enough rambling from me I’m sure all you care about is the code.  The first thing you need to do is modify your Manifest file to allow access to the users phone account.

<uses-permission android:name="android.permission.MANAGE_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.USE_CREDENTIALS"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

That out of the way, you could use this code in conjunction with a loading dialog or any other method that works best for you..

	private String updateToken(boolean invalidateToken) {
		String authToken = "null";
		try {
			AccountManager am = AccountManager.get(context);
			Account[] accounts = am.getAccountsByType("com.google");
			AccountManagerFuture<Bundle> accountManagerFuture;
			if(activity == null){//this is used when calling from an interval thread
				accountManagerFuture = am.getAuthToken(accounts[0], "android", false, null, null);
			} else {
				accountManagerFuture = am.getAuthToken(accounts[0], "android", null, activity, null, null);
			}
			Bundle authTokenBundle = accountManagerFuture.getResult();
			authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN).toString();
			if(invalidateToken) {
				am.invalidateAuthToken("com.google", authToken);
				authToken = updateToken(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return authToken;
	}

And there you have it. You now have a token that can be used with many of the Google services. This took a few hours of research on my part so hopefully this will save someone the trouble.

13 Comments :, , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!