0

I have to fetch logged in email. I am trying to fetch using AccountManager. Here is my code

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));
            }
        }
    }

I tried both option AccountManager.get(this).getAccountsByType("com.google"); AccountManager.get(this).getAccounts();

Both are returning empty body.

Please help me.

Amit Yadav
  • 32,664
  • 6
  • 42
  • 57

1 Answers1

1

Add permission

android.permission.GET_ACCOUNTS

Kotlin implementation

val manager = getSystemService(ACCOUNT_SERVICE) as AccountManager
    manager.accounts.forEach {
        if(it.type.equals("com.google",true))
         {
           Log.e(TAG,"${it.name}")
         }
     }

After some more research I came to know that you should have below permission as well.

Manifest.permission.READ_CONTACTS

Request permission at runtime

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);

Java implementation

 AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    
            for (Account account : manager.getAccounts()) {
                if (account.type.equalsIgnoreCase("com.google")) {
                    Log.e(TAG, "Mail: "+account.name);
                }
            }

User Thomas Thomas states the above permission is necessary as well Reference

Ammar Abdullah
  • 802
  • 4
  • 8
  • 21