Java – Is there an official way to authenticate to Google Data APIs on Android using an AccountManager account?

Is there an official way to authenticate to Google Data APIs on Android using an AccountManager account?… Here is a solution to the problem.

Is there an official way to authenticate to Google Data APIs on Android using an AccountManager account?

I’m trying to use the Google Data API for an app installed on Android 2.1. If the user has already configured an account on the device, I don’t want the user to have to enter their credentials. So I’m using AccountManager with an account type of “com.google”.

But where to go from there? Google has no examples of how to do Google authentication (authTokenType, etc.). There is a project that has tried to do this in a general way (http://code.google.com/p/google-authenticator-for-android), but it has not been successful yet.

Can it be so hard? This really hinders apps like the Google Reader client, which have to ask users for their Google credentials (hopefully no one gives them).

Any pointers/suggestions are welcome.

The best answer

Yes, it is possible. Once you have a Google Account (as you described), you can simply request an authorization token for the GData service from AccountManager.

If the Android device already has an authorization token (for the specific GData service you are trying to access), it will be returned to you. If not, AccountManager will request one and return it to you. Either way, you don’t need to worry because AccountManager takes care of it.

In the following example, I’m 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");

}

Hope this helps.

About java – Is there an official way to authenticate to Google Data API on Android using an AccountManager account? , we found a similar problem on Stack Overflow:

https://stackoverflow.com/questions/3492775/