I want to prepopulate some of the fields in my application to help out user when he is subscribing for the service inside my app.
So how would I get first name and last name of device's owner. I want to use default info tied to Google account; so far I got this:
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
for (Account account : accounts) {
if (account.type.compareTo("com.google") == 0)
{
String possibleEmail = account.name;
// how to get firstname and lastname here?
}
}
I am willing to take alternative approaches if you suggest them - just as long as I can get email, firstname and lastname of the owner.
In Ice Cream Sandwich getting this information is easy, as Android includes a personal profile that represents the device owner - this profile is known as the "Me" profile and is stored in the ContactsContract.Profile
table. You can read data from the user's profile so long as you request the READ_PROFILE
and the READ_CONTACTS
permissions in your AndroidManifest.xml.
The most relevant fields for you are the DISPLAY_NAME column from the Contact and possibly the StructuredName fields - stuff like the user's contact photo is also available.
There's an Android Code Lab tutorial that gives a full example of reading a user's profile, the core bit of code is in the ListProfileTask
. Here's an abridged snippet:
Cursor c = activity.getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
int count = c.getCount();
String[] columnNames = c.getColumnNames();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
String columnName = columnNames[j];
String columnValue = c.getString(c.getColumnIndex(columnName)));
...
// consume the values here
}
}
c.close();
I don't think there's a way of getting this kind of data before API-level 14, unfortunately.