How to get registered Email address programmatically in Android Android 05.04.2018

How to get registered Email address programmatically in Android

In this tutorial, you will learn to get and display registered email address programmatically in Android application.

Using AccountPicker

Add Google Account Login to the dependencies in your build.gradle file:

dependencies {
    ...
    implementation 'com.google.android.gms:play-services-auth:12.0.0'
}

Request email

Intent googlePicker = AccountPicker
    .newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, 
    true, null, null, null, null);
startActivityForResult(googlePicker, REQUEST_CODE);

Response with email

protected void onActivityResult(final int requestCode, final int resultCode, 
        final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        Log.d(TAG, accountName);
    }
}

Using AccountManager

To get registered email address in Android we have to use AccountManager class, this allows us to access to get registered user email address/account from android device.

AccountManager class provides access to all registered user accounts in device. AccountManager generates the auth tokens for different applications and caches it. It is also responsible for periodic check for the validity of auth tokens.

We have to use GET_ACCOUNTS permission. It is the dangerous permissions and from the Android Marshmallow 6.0 it can be used as runtime permissions. So user can himself decide to allow it or not.

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Following is AccountsActivity.java.

public class AccountsActivity extends AppCompatActivity {
    private String TAG = "AccountsActivityTAG";
    private String wantPermission = Manifest.permission.GET_ACCOUNTS;
    private Activity activity = AccountsActivity.this;
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accounts);

        if (!checkPermission(wantPermission)) {
            requestPermission(wantPermission);
        } else {
            getEmails();
        }
    }

    private void getEmails() {
        Pattern emailPattern = Patterns.EMAIL_ADDRESS;

        // Getting all registered Google Accounts;
        // Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");

        // Getting all registered Accounts;
        Account[] accounts = AccountManager.get(this).getAccounts();

        for (Account account : accounts) {
            if (emailPattern.matcher(account.name).matches()) {
                Log.d(TAG, String.format("%s - %s", account.name, account.type));
            }
        }
    }

    private boolean checkPermission(String permission){
        if (Build.VERSION.SDK_INT >= 23) {
            int result = ContextCompat.checkSelfPermission(activity, permission);
            if (result == PackageManager.PERMISSION_GRANTED){
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    private void requestPermission(String permission){
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)){
            Toast.makeText(activity, "Get account permission allows us to get your email",
                Toast.LENGTH_LONG).show();
        }
        ActivityCompat.requestPermissions(activity, new String[]{permission}, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getEmails();
                } else {
                    Toast.makeText(activity,"Permission Denied.",
                            Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
}