ArewegoodQ ArewegoodQ - 1 month ago 10
Android Question

Get all Registered Email Accounts in Android

I basically want to give option to user to select the email ID user wants. I don't want the contacts permission from user. Though account permission is fine with user. I tried answer at stackoverflow but it is not working for me. Is there any other way of getting it?

What I have tried:

Add this permission to manifest:

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


And then request the google accounts like this:

Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
for (Account account : accounts) {
Log.d(TAG, "Found: " + account.name);
}

Answer

You can try this way. It basically pops up all the registered emails that are logged in on the device.

Button btnEmail = (Button) findViewById(R.id.btn_email);
btnEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                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:
                    Toast.makeText(Login.this, "Error: " + e, Toast.LENGTH_SHORT).show();
                }
            }
        });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_EMAIL && resultCode == RESULT_OK) {
            userEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            btnEmail.setText(userEmail);
            email_OK = true;
        }
    }

Tell me if you find it not working.