Android: AccountManager.getAccounts() returns an empty array

user2223059 picture user2223059 · Jan 28, 2016 · Viewed 12.8k times · Source

I'm writing an app targeted at Lollipop and above. This is my first Android app.

I'm trying to get a list of all the accounts that are associated with the device. Here is my code:

public void getAllContactsAccounts(Context context){
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    Account[] accounts = accountManager.getAccounts();
    System.out.println("PrintingAccounts: " + accounts.length);
    for(Account a : accounts){
        System.err.println("AccountName: " + a.name);
    }
}

The array from accountManager.getAccounts() ends up having a length of 0, and nothing happens.

I can't figure out how to fix this. I've added the necessary permissions (plus a few others), no security exception happens, the app runs fine, but it just can't seem to retrieve the accounts.

Any advice on what I can do here?

Answer

abhilash maddukuri picture abhilash maddukuri · Apr 18, 2018

From Android 8.0, GET_ACCOUNTS is no longer sufficient to access the Accounts on device.

Based on the documentation:

In Android 8.0 (API level 26), apps can no longer get access to user accounts unless the authenticator owns the accounts or the user grants that access. The GET_ACCOUNTS permission is no longer sufficient. To be granted access to an account, apps should either use AccountManager.newChooseAccountIntent() or an authenticator-specific method. After getting access to accounts, an app can call AccountManager.getAccounts() to access them.

You can check this link for usage of AccountManager.newChooseAccountIntent()