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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With