Can't get default account in OREO
Asked Answered
A

1

2

In Android Oreo, AccountManager.getAccountsByType("com.google"); returns null.

Its, working fine in below Android 8 versions.

Below is my code:

private static Account getAccount(AccountManager accManager) {
    Account[] accounts = accManager.getAccountsByType("com.google");
    Account account;
    if (accounts.length > 0) {
        account = accounts[0];
    } else {
        account = null;
    }
    return account;
}

Thanks in advance.

Anagoge answered 8/3, 2018 at 9:32 Comment(1)
Possible duplicate of Android 8.0 Oreo - AccountsPepperandsalt
W
0

As per Android's update, from Oreo onwards we can not use AccountManager.getAccountsByType to get the list of google accounts configured on user's device, as they have updated the Google SignIn features. The new feature will prompt the user to select the account and that account will be only visible to our app.

See the documentation: https://developer.android.com/about/versions/oreo/android-8.0-changes#aaad

If you still want to continue with the old approach of showing all the account's to users, you need to get an extra consent from user by doing below procedures.

You can use GoogleAuthUtil.requestGoogleAccountsAccess to get the list of Google accounts.

A sample code is given below:

new Thread(() -> {
            try {
                GoogleAuthUtil.requestGoogleAccountsAccess(getApplicationContext());
            } catch (Exception e) {
                if (e instanceof UserRecoverableAuthException) {
                    startActivityForResult(((UserRecoverableAuthException) e).getIntent(),
                            REQ_CODE_PERMISSION_GET_GOOGLE_ACCOUNTS);
                } else {
                    Log.e("SignIn", "Exception in getting google accounts" + e);
                }
            }

        }).start();

This will create an activity to prompt user to accept the consent to allow Google Play Service to access the list of google accounts configured on the device.

You can then override onActivityResult() function on your activity to continue after.

Then you can use AccountManager.getAccountsByType to get the list of google accounts as you done before.

Happy Coding!

Wintergreen answered 9/12, 2018 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.