getAccountsByType(“ com.google”)无法列出我的minSdkVersion 21和targetSdkVersion 27的Google帐户

时间:2018-09-22 13:55:54

标签: android kotlin android-permissions

我正试图从docsGoogle Account手机上获取Nexus

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

即使我绝对有一个帐户,并且可以看到引用该帐户的日志,例如I/TrustAgent: [HomeAddressChangeTracker] fetch for account myaddress@gmail.com,并且我已经添加了权限并验证了它们的授予权限,但该数组始终为空。

我有minSdkVersion 21targetSdkVersion 27

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

根据changes in 8.0,不能仅凭GET_ACCOUNTS权限访问帐户。您还需要要求用户使用AccountManager.newChooseAccountIntent选择帐户,如下所示:

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

AccountManager.newChooseAccountIntent文档中所述:

  

已选择的帐户被标记为对调用方为VISIBILITY_USER_MANAGED_VISIBLE(请参阅setAccountVisibility(Account,String,int)),并将在随后的getAccountsByType(String))调用中返回给该帐户。

因此您只需要选择一次帐户,然后系统就应该记住此选择,以便随后调用AccountManager.getAccountsByType