-1

I am on a project that I need to list all accounts (Gmail, Exchange, etc.) in the users device.

First things first; my code snippet is below;

public class MainActivity extends AppCompatActivity {
    public static final int PERMS_REQUEST_CODE = 1;
    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.GET_ACCOUNTS)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, PERMS_REQUEST_CODE);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, PERMS_REQUEST_CODE);
            }
        } else {
            AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
            Account[] accounts = manager.getAccounts();
            Log.d(LOG_TAG, "Done! List of accounts: " + accounts.length);
        }
    }
}

It shows below screen, as expected, and I allow it;

Request of accessing Contacts

But then, the list of accounts retrieved in the line below is empty;

Account[] accounts = manager.getAccounts();

I have an account on the device, by the way;

List of accounts on the device

What I am missing?

Note: I searched the web and questions like this but no way. They point to "lack of permissions" but my app has.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Taner
  • 4,511
  • 3
  • 18
  • 14
  • Are you saying, after you grant the permission, and restart `MainActivity`, the `accounts` array in the `else` block is empty? Or are you calling that elsewhere in the `Activity`, too, like in `onRequestPermissionsResult()`? – Mike M. Apr 23 '19 at 10:18
  • @MikeM. Yes, the point is exactly this; after I grant the permission, and restart MainActivity, the accounts array in the else block is empty. – Taner Apr 23 '19 at 10:24
  • 1
    OK, just makin' sure I was following you correctly. Have a look here: https://stackoverflow.com/q/35050548. – Mike M. Apr 23 '19 at 10:29
  • 1
    I inspected the link you gave and being routed to a weird solution: adding the Manifest.permission.READ_CONTACTS both to Manifest and runtime permission request. Thanks. – Taner Apr 23 '19 at 10:39

1 Answers1

0

As @MikeM.'s comment; adding Manifest.permission.READ_CONTACTS both to Manifest and runtime permission request solved this. Weird but working...

Thanks

Taner
  • 4,511
  • 3
  • 18
  • 14