如何使用适用于Android的Gmail API获取用户名?

时间:2016-05-23 19:38:41

标签: android rest gmail-api

我正在创建一个Android应用程序,我在其中提供Gmail登录。我需要得到用户的名字。我正在从Google提供的教程中获取帮助,以整合Gmail(链接:https://developers.google.com/gmail/api/quickstart/android#step_5_setup_the_sample

我没有使用REST API的经验。谁能告诉我怎么得到这个名字?

1 个答案:

答案 0 :(得分:0)

按名称,您的意思是电子邮件地址/用户名或用户名。如果您正在寻找电子邮件,那么您可以使用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