codepath / android_guides

Extensive Open-Source Guides for Android Developers
guides.codepath.com
MIT License
28.29k stars 6.35k forks source link

AccountManager #49

Open nesquena opened 9 years ago

nesquena commented 9 years ago

http://stackoverflow.com/questions/2112965/how-to-get-the-android-devices-primary-e-mail-address https://gist.github.com/remelpugh/4072663 http://geekgarage.dad3zero.net/contact-informations-and-respect-privacy-android-development/ http://developer.android.com/reference/android/telephony/TelephonyManager.html http://developer.android.com/reference/com/google/android/gms/common/AccountPicker.html

nesquena commented 9 years ago

From Nicole:

To get the user's name, if you are only supporting Android 4.0+, you can use the "me" contact in the Contacts list. (I'll add example code at the end). This requires both READ_CONTACTS and READ_PROFILE permission.

To get the user's phone number you can use the TelephonyManager: http://developer.android.com/reference/android/telephony/TelephonyManager.html (This requires the READ_PHONE_STATE permission)

Getting their e-mail address is a bit trickier. The AccountManager has all the details of the accounts the user has on their device (really, all of them) but there could be multiple email accounts. (In fact, there can be multiple Google accounts).

But there's a way around that little problem! AccountPicker shows a list of accounts to the user and allows them to chose which one they'd like to use for their data: http://developer.android.com/reference/com/google/android/gms/common/AccountPicker.html

If you use the AccountPicker (with the example usage they have there, which prompts for Google accounts) then you don't need the GET_ACCOUNTS permission, which is nice.

To read the user's name from Contacts:

private String getUserName(final Context context) {
    final String[] projection = new String[] { ContactsContract.Profile.DISPLAY_NAME };
    final Uri dataUri = Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
            ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
    final Cursor c = context.getContentResolver().query(dataUri, projection, null, null, null);
    try {
        if (c.moveToFirst()) {
            return c.getString(c.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME));
        }
    } finally {
        c.close();
    }

    // Couldn't find it
    return null;
}