Finding Google Account on Multiple Android Versions

Finding Google Account on Multiple Android Versions

Cell phone pile  CCCBIf you want to develop for the most Android devices, chances are you will run across something you need to do differently depending on the age of the device at hand. Newer API's contain different features from old ones.

There's a slick little trick whereby you can handle multiple API versions easily. For instance, finding the Google email address(es) on the phone is a challenge for anything that bridges the "Eclair" threshold. I finally kludged together from multiple sources a working example - nobody handled it quite correctly to do this from any one example I found - although this one came close.

Create an abstract class that manages the details for you like so:


 


import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.os.Build;

public abstract class GoogleAccountsWrapper {
public static GoogleAccountsWrapper getInstance() {
if (Integer.parseInt(Build.VERSION.SDK) < 5)
{
return PreEclair.Holder.instance;
}
else
{
return EclairPlus.Holder.instance;
}
}

public abstract String[] initGMailAccount(Activity activity);

private static class PreEclair extends GoogleAccountsWrapper
{
private static class Holder {
private static final PreEclair instance = new PreEclair();
}
Override
public String[] initGMailAccount(Activity activity) {
com.google.android.googlelogin.GoogleLoginServiceHelper
                           .getAccount(activity, 12345, true);
return null;
}

}

private static class EclairPlus extends GoogleAccountsWrapper
{
private static class Holder {
private static final EclairPlus instance = new EclairPlus();
}
Override
public String[] initGMailAccount(Activity activity) {
int mycount = 0;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccounts();
mycount = accounts.length;
if (mycount < 1) {
return null;
}
String[] mystrings = new String[mycount];
int i =0;
for(Account account: accounts) {
mystrings[i] = account.name;
i++;
}
return mystrings;
}

}

}

Now, you can do something like this from your app:

GoogleAccountsWrapper myaccounts = GoogleAccountsWrapper.getInstance();
String[] accounts = myaccounts.initGMailAccount(this);
if (accounts != null) {
  ...

And don't forget to override the OnActivityResult and read the accounts from the data provided there, if it happens (the old method.)

Posted by Tony on Feb 14, 2011 | Android Development