如何在Android中检索我登录的Google帐户的名字和姓氏?

时间:2016-12-26 11:23:31

标签: android google-authentication

我有一个简单的google authentification应用程序,我想显示一条欢迎消息。如果电子邮件帐户是j ohnsmith@gmail.com ,我想要Toast "欢迎John Smith!" 我该怎么办?去做?

这是我的代码:

if (user == null) {
        startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE);
    } else {
        Toast.makeText(MainActivity.this, "Welcome " + userName, Toast.LENGTH_SHORT).show();
    }

我尝试使用此代码,但我只获取用户名,而不是名字和姓氏。

AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();

提前致谢!

2 个答案:

答案 0 :(得分:2)

<强> onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent result) {
    if (requestCode == GOOGLE_REQUEST_CODE) { // Google + callback
       handleSignInResult(Auth.GoogleSignInApi.getSignInResultFromIntent(result));
       }
}

handleSignInResult

private void handleSignInResult(GoogleSignInResult googleSignInResult) {
    if (googleSignInResult.isSuccess()) {
        GoogleSignInAccount acct = googleSignInResult.getSignInAccount();
        if (acct != null) {
            //get the data you need from GoogleSignInAccount
            }
        } else {
            Toast.makeText(context.getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
        }
    }

您可以在GoogleSignInAccount上找到更多信息: https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount

答案 1 :(得分:0)

好的编辑回答 -

Cursor c = activity.getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
int count = c.getCount();
String[] columnNames = c.getColumnNames();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
    String columnName = columnNames[j];
    String columnValue = c.getString(c.getColumnIndex(columnName)));
    ...
    //Use the values
    }
}
c.close();

j = 0代表DISPLAY_NAME。

但这只能从ICS开始提供。在AndroidManifest中添加READ_PROFILE和READ_CONTACTS权限。