使用Credential Manager完成谷歌登录后如何获取android.accounts.Account?
解决方案
方法一:通过邮箱查找系统中的Google Account
从GetCredentialResponse中提取用户邮箱后,可通过AccountManager查找对应的android.accounts.Account:
- 提取邮箱信息
从GoogleIdTokenCredential中解析出用户邮箱:
// 从GetCredentialResponse获取GoogleIdTokenCredential val googleCredential = credentialResponse.credential as GoogleIdTokenCredential // 从idToken的Claims中取出邮箱 val userEmail = googleCredential.idTokenClaims["email"] as String
- 通过AccountManager获取Account
使用AccountManager根据邮箱和Google账户类型查找目标账户:
val accountManager = AccountManager.get(activity) // 查询所有Google类型的账户 val googleAccounts = accountManager.getAccountsByType("com.google") // 匹配邮箱对应的账户 val targetAccount = googleAccounts.find { it.name == userEmail }
- 处理空值情况
如果targetAccount为null,说明系统中没有该邮箱对应的Google账户,可能需要引导用户添加账户,或者改用方法二直接调用API。
方法二:直接用IdToken调用People API(无需Account对象)
不需要依赖GoogleAccountCredential和android.accounts.Account,直接用Credential Manager获取的IdToken作为请求凭证:
- 构建自定义请求初始化器
用IdToken设置Authorization请求头:
val idToken = googleCredential.idToken val requestInitializer = HttpRequestInitializer { request -> request.headers.setAuthorization("Bearer $idToken") }
- 初始化PeopleService
用自定义的requestInitializer替代GoogleAccountCredential:
val peopleService = PeopleService.Builder( GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), requestInitializer ) .setApplicationName("Your Application Name") .build()
- 调用API获取性别和生日
后续调用逻辑和你原来的代码一致:
viewModelScope.launch { try { val response = withContext(Dispatchers.IO) { peopleService.people().get("people/me") .setPersonFields("birthdays,genders") .execute() } val birthdays = response?.birthdays val genders = response?.genders // 处理获取到的数据 } catch (e: Exception) { e.printStackTrace() } }
注意事项
- 确保在Credential Manager登录请求中,已声明所需的权限Scope:
https://www.googleapis.com/auth/userinfo.profile、https://www.googleapis.com/auth/user.birthday.read、https://www.googleapis.com/auth/user.gender.read,否则API调用会返回权限不足错误。 - 方法一中,Android 10及以上版本需要申请
GET_ACCOUNTS权限(在Manifest中添加<uses-permission android:name="android.permission.GET_ACCOUNTS" />),并动态请求权限。
内容的提问来源于stack exchange,提问作者hmmmmm
相关产品推荐
相关产品推荐

