Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getAccountsByType("com.google") fails to list my Google Account for minSdkVersion 21 and targetSdkVersion 27

From the docs I am trying to get the Google Account on my Nexus phone:

val am: AccountManager = AccountManager.get(this)
val myAccounts: Array<Account> = am.getAccountsByType("com.google")

Even though I definitely have an account and can see logs refering to it such as I/TrustAgent: [HomeAddressChangeTracker] fetch for account [email protected] AND I have added the permissions and verified they are granted, the array is always empty.

I have minSdkVersion 21 and targetSdkVersion 27

Any ideas?

like image 387
Dave Chambers Avatar asked Sep 22 '18 13:09

Dave Chambers


1 Answers

As per changes in 8.0, accounts aren't accessible just with the GET_ACCOUNTS permission. You also need to require the user to choose an account using AccountManager.newChooseAccountIntent like so:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    if(checkSelfPermission(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
        val intent = AccountManager.newChooseAccountIntent(null, null, arrayOf("com.google"), null, null, null, null)
        startActivityForResult(intent, 42)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    if (requestCode == 42) 
        val accountManager = AccountManager.get(this)
        val accounts = accountManager.getAccountsByType("com.google")
        accounts.forEach {
            Log.v(localClassName, it.toString())
        }
    }
}

As noted in the documentation for AccountManager.newChooseAccountIntent:

Chosen account is marked as VISIBILITY_USER_MANAGED_VISIBLE to the caller (see setAccountVisibility(Account, String, int)) and will be returned to it in consequent getAccountsByType(String)) calls.

so you should only have to choose the account once, and then the system should remember this choice for subsequent calls to AccountManager.getAccountsByType.

like image 69
msbit Avatar answered Nov 16 '22 20:11

msbit