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

我有一个简单的google authentification应用程序,我想显示一条欢迎消息。 如果电子邮件帐户是j ohnsmith@gmail.com ,我想要一个Toast with “欢迎约翰史密斯!” 我怎样才能做到这一点?

这是我的代码:

 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(); 

提前致谢!

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上find更多GoogleSignInAccount : https : //developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount

好的编辑答案 –

 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权限。