I'm working on Android sign in with Google and hope to get the account's gender and birthday after successfully sign in. I can successfully get the birthday by using GoogleSignIn and People api. However, I notice that GoogleSignIn is deprecated and Credential Manager is recommended. After I successfully sign in by following this document:https://developer.android.com/identity/sign-in/credential-manager-siwg, the result is GetCredentialResponse. I can get idToken, name, id, etcs from this GetCredentialResponse. But GoogleAccountCredential need to set the Account, which is android.accounts.Account. Anyone know how I can get the account according GetCredentialResponse/idToken? Thanks.
private fun getAdditionalUserInfo(
activity: Activity,
account: GoogleSignInAccount,
) {
val credential = GoogleAccountCredential.usingOAuth2(
activity,
listOf(
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/user.birthday.read",
"https://www.googleapis.com/auth/user.gender.read"
)
)
credential.selectedAccount = account.account
val peopleService = PeopleService.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
GsonFactory.getDefaultInstance(),
credential
)
.setApplicationName("Your Application Name")
.build()
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
_isAccountPickerViewVisible.value = false
_googleIdTokenCredential.value =
"birthday:$birthdays\n" +
"genders: $genders"
} catch (e: Exception) {
e.printStackTrace()
}
}
}
The Account class has a constructor that takes an email and a type. You can get the email from the GoogleIdTokenCredential (the 'id' field) and for the type, use "com.google", so you can build an account object:
Account account = new Account(googleIdTokenCredential.getId(), "com.google");
As a side note, you can also use the Authorization APIs as well, to get the tokens that you want after the sign-in.