I am getting email id by using android.permission.GET_ACCOUNTS
permission.
try {
Account[] accounts = AccountManager.get(this).getA
Example as a separate service class to be easily used in different situations by calling getGMailAccount method.
public class GMailAccountService {
private static final int MIN_SDK_FOR_REQUESTING_GET_ACCOUNTS = 22;
private static final int GET_ACCOUNTS_PERMISSION_REQUEST_CODE = 112;
private Activity activity;
public GMailAccountService(Activity activity) {
this.activity = activity;
}
public String getGMailAccount() {
if(android.os.Build.VERSION.SDK_INT > MIN_SDK_FOR_REQUESTING_GET_ACCOUNTS){
if(!isGetAccountsPermissionAllowed()){
requestGetAccountsPermission();
return getGMailAccount();
}
}
return extractAddressFromAccountManager();
}
private boolean isGetAccountsPermissionAllowed() {
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS);
if (result == PackageManager.PERMISSION_GRANTED)
return true;
return false;
}
private void requestGetAccountsPermission(){
ActivityCompat.shouldShowRequestPermissionRationale(activity, android.Manifest.permission.GET_ACCOUNTS);
ActivityCompat.requestPermissions(activity,new String[]{android.Manifest.permission.GET_ACCOUNTS}, GET_ACCOUNTS_PERMISSION_REQUEST_CODE);
}
public String extractAddressFromAccountManager(){
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8
Account[] accounts = AccountManager.get(activity).getAccountsByType("com.google");
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
return account.name;
}
}
return null;
}
}