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" />
please add this permission in your manifest file.
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Add this function in your MainActivity.java
public void getAccounts() {
StringBuilder emailAccounts = new StringBuilder();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.GET_ACCOUNTS)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
}
}
else {
List<String> accountList = new ArrayList<String>();
Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
if (gmailPattern.matcher(account.name).matches()) {
emailAccounts.append(flag + ". " + "<b>" + account.name + "<br>" +
"---------" + "---------<br>"); ;
}
}
deviceDetails.setText(Html.fromHtml(emailAccounts+""));
}
}
now call this function in your onCreate() method like this.
getAccounts();