Issue
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.
Solution
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
Answered By - Ammar Abdullah
Answer Checked By - Gilberto Lyons (JavaFixing Admin)