【发布时间】:2016-09-20 19:37:11
【问题描述】:
我正在创建一个我提供 Gmail 登录的 Android 应用程序。我需要获取用户的名称。我正在从 Google 提供的集成 Gmail 的教程中获得帮助(链接:https://developers.google.com/gmail/api/quickstart/android#step_5_setup_the_sample)
我没有任何使用 REST API 的经验。谁能告诉我怎么取名字?
【问题讨论】:
我正在创建一个我提供 Gmail 登录的 Android 应用程序。我需要获取用户的名称。我正在从 Google 提供的集成 Gmail 的教程中获得帮助(链接:https://developers.google.com/gmail/api/quickstart/android#step_5_setup_the_sample)
我没有任何使用 REST API 的经验。谁能告诉我怎么取名字?
【问题讨论】:
您的姓名是指电子邮件地址/用户名还是用户名。如果您正在寻找电子邮件,那么您可以使用 Users:getProfile Class 获取它。
GET https://www.googleapis.com/gmail/v1/users/userId/profile
示例响应:
{
"emailAddress": string,
"messagesTotal": integer,
"threadsTotal": integer,
"historyId": unsigned long
}
但是如果你想获取用户的名字,你可以试试Google Sign-In for Android。
// Configure sign-in to request the user's ID, email address, and basic profile. ID and
// basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
// Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
然后,当点击登录按钮时,启动登录意图:
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
系统会提示用户选择要登录的 Google 帐户。如果您请求的范围超出个人资料、电子邮件和 openid,系统还会提示用户授予对所请求资源的访问权限。
最后,处理活动结果:
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from
// GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
// Get account information
mFullName = acct.getDisplayName();
mEmail = acct.getEmail();
}
}
}
HTH
【讨论】: