2016-12-26 79 views
5

我有一个简单的应用程序与谷歌认证,我想显示一个欢迎消息。如果电子邮件帐户是j [email protected],我想要一个Toast“欢迎John Smith!”我该怎么做?如何在Android中检索我登录的Google帐户的名和姓?

这是我的代码:

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

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

你可以找到更多关于GoogleSignInAccounthttps://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount

+0

我终于做到了。这个答案帮了我。谢谢! –

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

+0

谢谢,但正如我已经说过,我用这个代码。我只获取用户名。我需要第一个和最后一个名字。 –

+0

他只需要名字不是带ID的全名。 – sukumar

+0

@AlexM。看到编辑的答案。如果以任何方式帮助你,请接受答案。谢谢:) – iamgopal

相关问题