开发者

Android - Get UserData using AccountManager / First and Last name of the phone owner

开发者 https://www.devze.com 2023-04-03 17:04 出处:网络
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.

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:

Acco开发者_如何学编程untManager 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.


Here is how i did that (also from api 14):

public class MainActivity implements LoaderManager.LoaderCallbacks<Cursor> {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportLoaderManager().initLoader(0, null, this);
}



@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(
                    ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
            ProfileQuery.PROJECTION,

            // Select only  name.
            ContactsContract.Contacts.Data.MIMETYPE + "=?",
            new String[]{ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE},

            // Show primary fields first. Note that there won't be
            // a primary fields if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    User user = new User();
    List<String> names = new ArrayList<>();
    cursor.moveToFirst();
    String mimeType;
    while (!cursor.isAfterLast()) {
        mimeType = cursor.getString(ProfileQuery.MIME_TYPE);
        switch (mimeType) {

            case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
                String name = cursor.getString(ProfileQuery.GIVEN_NAME) + " " + cursor.getString(ProfileQuery.FAMILY_NAME);
                if (!TextUtils.isEmpty(name)) {
                    names.add(name);
                }
                break;
        }
        cursor.moveToNext();
    }

    if (!names.isEmpty()) {
        // do with names whatever you want
    }
}



@Override
public void onLoaderReset(Loader<Cursor> loader) {

}

private interface ProfileQuery {
    String[] PROJECTION = {
            ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
            ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
            ContactsContract.Contacts.Data.MIMETYPE
    };


    /**
     * Column index for the family name in the profile query results
     */
    int FAMILY_NAME = 0;
    /**
     * Column index for the given name in the profile query results
     */
    int GIVEN_NAME = 1;
    /**
     * Column index for the MIME type in the profile query results
     */
    int MIME_TYPE = 2;
}

And there should be permissions:

<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
0

精彩评论

暂无评论...
验证码 换一张
取 消