android - 在使用 Google 登录后,在应用程序中获取生日

标签 android google-play-services google-signin

我是按照官方文档实现sing-in with Google的。这并不困难,但官方文档止于获取姓名或电子邮件等基本信息。我需要过生日。

所以,在创建选项时,我添加了这个:

.requestScopes(Scope("https://www.googleapis.com/auth/user.birthday.read"))

由于官方文档停在那里我不知道如何得到生日。因此,我在网上搜索并找到了一种使用普通 HTTP GET 请求到 https://people.googleapis.com/v1/people/me 的方法。 (或者这是否包含在 Google Play Services API 中?)

但该方法需要访问 token ,该 token 未包含在登录后返回的 GoogleSignInAccount 中。有一个通过创建 OAuth 服务器 ID 获取访问 ID 的示例,然后使用getServerAuthCode() 获取访问 token ,但这很复杂,而且它不是在服务器上完成的,它是在应用程序内部完成的,在登录后立即完成。

在这种情况下,我是否必须创建一个 OAuth 服务器 ID,并使用访问 token 来获取生日?

最佳答案

经过大量的 Google 搜索,我找到了 this example .在找到这个之前,我找到了一个使用 Plus.API 的例子,但是这个答案说它已被弃用。有趣的是,现在连这个答案都过时了,也不管用了。我不得不进行更多搜索才能修复它。如果只有 Google 的登录文档页面包含获取默认字段以外的其他数据的示例,那么所有这些痛苦都可以避免。

无论如何,这是对我有用的代码。

First, sign in with Google according to the official documentation.
Then,

val HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
val JSON_FACTORY = JacksonFactory.getDefaultInstance();

inner class DamnTask(var email:String) :AsyncTask<Unit,Unit,Unit>()
{
    override fun doInBackground(vararg params: Unit?)
    {
        var credential = GoogleAccountCredential.usingOAuth2(context,
                Collections.singletonList(Scopes.PROFILE));
        credential.selectedAccount = Account(email, "com.google");

        var service = People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("MyApp")
                .build();

        var me = service.people().get("people/me")
                .setRequestMaskIncludeField("person.Birthdays")
                .execute();
        Log.d("damn", "Birthday " +me.birthdays.toString());
    }
}

为了让它工作,我必须将以下库添加到依赖项中。

compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.api-client:google-api-client-android:1.22.0'
compile 'com.google.apis:google-api-services-people:v1-rev4-1.22.0'

另外,我必须在项目设置中启用“People”API。这需要在 Google 的网络控制台中完成。我忘记了 URL,但如果您不启用它,异常消息将显示启用它的确切 URL。

可以找到更多的字段名here .

关于android - 在使用 Google 登录后,在应用程序中获取生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222119/

相关文章:

android - Google Play 游戏服务成就 Activity 立即结束

android - 在库中使用外部 google-services.json 文件

android - Google 新登录,未调用 onActivityResult()

android - eclipse 中的谷歌播放服务错误

google-oauth - Google oauth 未关闭移动设备中的登录页面

android - 为什么Android模拟器是偶数?

java - 将对象添加到 ListView - ANDROID

android - 我想在 android Activity 底部为 "adview"横幅保留空间而不覆盖内容

android - 仪器测试 - setContentView() 上的空指针异常

android - com.google.android.gms :play-services-base compile and runtime collision in react native