Sunday, January 23, 2011

Super simple identification code

So I'm working on an Android app and I really don't care about authentication (yet) but need a way to identify a user. I can assume the user will have at least 1 google (or gmail) account and I'm also going to leverage off the Google App Engine for many services. I'll probably add in the AuthToken functionality eventually - hopefully the Authentication features of Android and Google App Engine will continue to improve in the meantime.

So here's a class that extends ListActivity:


Account[] mAccts;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// get google/gmail accounts
AccountManager acctMan = AccountManager.get(this);
mAccts = acctMan.getAccountsByType("com.google");

// put the account names into a String[]
String[] acctnames = new String[mAccts.length];
for (int i=0; i< mAccts.length; i++) {
acctnames[i] = mAccts[i].name;
}

this.setListAdapter(new ArrayAdapter(this, R.layout.accts_row, acctnames));
}


That will show the user a list of their Google accounts. Here's the onListItemClick:


super.onListItemClick(l, v, position, id);

// find the account clicked and send the intent on its way
Account acct = mAccts[position];
Intent i = new Intent(this, PayMain.class);
i.putExtra(PayMain.KEY_ACCT, acct);
startActivity(i);


In your target activity class (PayMain in this case), the account will be bundled into the Intent.

The XML files are basic for ListActivity programs. Make sure you ask for GET_ACCOUNTS permission in AndroidManifest.xml (plus USE_CREDENTIALS and INTERNET if you're going to get an AuthToken).

I ran this on my Droid X with 2 gmail accounts and it works fine. Works with no Google accounts also (says the user needs to get a Google account and try again). Having problems adding an account to the emulator. I believe I'm supposed to do it through Dev Tools but can't seem to get it to work. I'm able to add a gmail account to the email app but it's not added to the system as a real account. Plus I can't locate any good documentation of Dev Tools. Strange...

No comments:

Post a Comment