Skip to content Skip to sidebar Skip to footer

Android: Accountmanager.getaccounts() Returns An Empty Array

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:

Solution 1:

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()

Solution 2:

For some reason, I had to request "android.permission.READ_CONTACTS" too to access the accounts list. Seems like required permissions are:

android.permission.READ_CONTACTS

android.permission.GET_ACCOUNTS

Solution 3:

Since the SdkTarget 23 and above(Marshmallow 6.0) you need to ask the user for permissions to access via run-time

 int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;
    // Here, thisActivity is the current activityif (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.GET_ACCOUNTS)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.GET_ACCOUNTS)) {

            // Show an expanation to the user *asynchronously* -- don't block// this thread waiting for the user's response! After the user// sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.GET_ACCOUNTS},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);
    }
}
    String possibleEmail="";
    try{
        possibleEmail += "************* Get Registered Gmail Account *************\n\n";
        Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");

        for (Account account : accounts) {

            possibleEmail += " --> "+account.name+" : "+account.type+" , \n";
            possibleEmail += " \n\n";

        }
    }


     Log.i("EXCEPTION", "mails: " + possibleEmail);

a snippet that is in onCreate() use for reference only

Here's a reference of these changes and some Documentation

Post a Comment for "Android: Accountmanager.getaccounts() Returns An Empty Array"