Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an official way to authenticate for Google Data API on Android using AccountManager accounts?

I'm trying to use the Google Data API for an installed application on Android 2.1. I don't want the user to have to enter their credentials if he already has an account configured on the device. Thus, I'm using the AccountManager with Account type "com.google".

But where to go from there? There are no samples from Google on how to do Google authentication (authTokenType etc.). There's a project trying to do it (http://code.google.com/p/google-authenticator-for-android) in a general way but without any success, yet.

Can it be so hard? This is really keeping back applications like Google Reader clients which have to ask the user for their Google credentials (which hopefully nobody gives them).

Any pointers/advice is appreciated.

like image 752
Florian Thiel Avatar asked Aug 16 '10 11:08

Florian Thiel


1 Answers

Yes this is possible. Once you have a handle on the Google account (as you described), you just need to request an auth token from the AccountManager for the GData service.

If the android device already has an auth token (for the particular GData service you're trying to access), it will be returned to you. If not, the AccountManager will request one and return it to you. Either way, you don't need to worry about this as the AccountManager handles it.

In the following example, I am using the Google Spreadsheets API:

ArrayList<Account> googleAccounts = new ArrayList<Account>();

// Get all accounts 
Account[] accounts = accountManager.getAccounts();
  for(Account account : accounts) {
    // Filter out the Google accounts
    if(account.type.compareToIgnoreCase("com.google")) {
      googleAccounts.add(account);
    }
  }
AccountManager accountManager = AccountManager.get(activity);

// Just for the example, I am using the first google account returned.
Account account = googleAccounts.get(0);

// "wise" = Google Spreadheets
AccountManagerFuture<Bundle> amf = accountManager.getAuthToken(account, "wise", null, activity, null, null);

try {
  Bundle authTokenBundle = amf.getResult();
  String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);

  // do something with the token
  InputStream response = sgc.getFeedAsStream(feedUrl, authToken, null, "2.1");

}

I hope this helps.

like image 122
Joel Avatar answered Sep 28 '22 07:09

Joel