How can you get an Android user's email address?
Why you wanna do that?
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
/**
* This class uses the AccountManager to get the primary email address of the
* current user.
*/
public class UserEmailFetcher {
static String getEmail(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account account = getAccount(accountManager);
if (account == null) {
return null;
} else {
return account.name;
}
}
private static Account getAccount(AccountManager accountManager) {
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
account = null;
}
return account;
}
}
In your AnroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
How to get the Android device's primary e-mail address
There are several ways to do this, shown below.
As a friendly warning, be careful and up-front to the user when dealing with account, profile, and contact data. If you misuse a user's email address or other personal information, bad things can happen.
Method A: Use AccountManager (API level 5+)
You can use AccountManager.getAccounts
or AccountManager.getAccountsByType
to get a list of all account names on the device. Fortunately, for certain account types (including com.google
), the account names are email addresses. Example snippet below.
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
...
}
}
Note that this requires the GET_ACCOUNTS
permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
More on using AccountManager
can be found at the Contact Manager sample code in the SDK.
Method B: Use ContactsContract.Profile (API level 14+)
As of Android 4.0 (Ice Cream Sandwich), you can get the user's email addresses by accessing their profile. Accessing the user profile is a bit heavyweight as it requires two permissions (more on that below), but email addresses are fairly sensitive pieces of data, so this is the price of admission.
Below is a full example that uses a CursorLoader
to retrieve profile data rows containing email addresses.
public class ExampleActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
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 email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
// Potentially filter on ProfileQuery.IS_PRIMARY
cursor.moveToNext();
}
...
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
}
This requires both the READ_PROFILE
and READ_CONTACTS
permissions:
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
How can I get Primary Email Account of Android phone?
As far as I read, there is no concept of primary email id in android. and there is no way to get e-mail id associated with play store. so what I did is, I have fetched all gmail ids and took the last one, it is not the main email id, but it should be the first added google account in his device. so in normal use cases user won't play with his first added email id. so we can assume it as primary mail id.
How do I get the email address of currently logged in user? (Android Studio / Java / Firebase)
You need to use mAuth
from firebase after your users logged in.
First declare the auth
private FirebaseAuth mAuth;
then initialize it (onCreate)
mAuth = FirebaseAuth.getInstance();
and then after the user is logged in you can get the email:
String email = mAuth.getCurrentUser().getEmail();
That's all.
ps: Also, after calling getCurrentUser()
. you can get a lot of things from the user , like user ID, user photo url , user metadata, user display name and more !
Getting Android owner's email address nicely
I know I'm way too late, but this might be useful to others.
I think the best way to auto-populate an email field now is by using AccountPicker
If your app has the GET_ACCOUNTS permission and there's only one account, you get it right away. If your app doesn't have it, or if there are more than one account, users get a prompt so they can authorize or not the action.
Your app needs to include the Google Play Services auth library com.google.android.gms:play-services-auth
but it doesn't need any permissions.
This whole process will fail on older versions of Android (2.2+ is required), or if Google Play is not available so you should consider that case.
Here's a basic code sample:
private static final int REQUEST_CODE_EMAIL = 1;
private TextView email = (TextView) findViewById(R.id.email);
// ...
try {
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE }, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_EMAIL);
} catch (ActivityNotFoundException e) {
// TODO
}
// ...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_EMAIL && resultCode == RESULT_OK) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
email.setText(accountName);
}
}
Getting the Gmail Id of the User In Android
As per my knowledge the user has to configure his gmail account in his android phone and then he gets access to Google Play.
You can fetch the account information as given below (from Jim Blackler):
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
/**
* This class uses the AccountManager to get the primary email address of the
* current user.
*/
public class UserEmailFetcher {
static String getEmail(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account account = getAccount(accountManager);
if (account == null) {
return null;
} else {
return account.name;
}
}
private static Account getAccount(AccountManager accountManager) {
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
account = null;
}
return account;
}
}
In Manifest
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Related Topics
How to Implement Enum with Generics
Null Check Chain VS Catching Nullpointerexception
Turning Off Hibernate Logging Console Output
In Java, Are Enum Types Inside a Class Static
How to Delete a File on Google Drive Using Google Drive Android API
How One Interface Can Be Used for Different Background Android Tasks
Can't Get Download Url from Firebase Storge in Android
How to Skip Initial Data and Trigger Only New Updates in Firestore Firebase
Navigation View Items Will Not Respond When Pressed
Android Studio Error: "Manifest Merger Failed: Apps Targeting Android 12"
How to Know Whether I am in a Call on Android
Android: Dex Cannot Parse Version 52 Byte Code
Is Custom Enum Serializable Too
What's a Good Library for Parsing Mathematical Expressions in Java
Which Android Data Storage Technique to Use