How to get profile like gender from google signin in Android?
UPDATE:
Since Plus.PeopleApi has been deprecated in Google Play services 9.4 as Google's declaration notes, please refer to the following solutions using Google People API instead:
Get person details in new google sign in Play Services 8.3
(Isabella Chen's answer);Cannot get private birthday from Google Plus account although explicit request
END OF UPDATE
First of all, make sure you have created Google+ profile for your Google account. Then you can refer to the following code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.PLUS_LOGIN))
.requestEmail()
.build();
and
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(Plus.API)
.build();
Then
@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);
handleSignInResult(result);
// G+
Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
Log.i(TAG, "--------------------------------");
Log.i(TAG, "Display Name: " + person.getDisplayName());
Log.i(TAG, "Gender: " + person.getGender());
Log.i(TAG, "AboutMe: " + person.getAboutMe());
Log.i(TAG, "Birthday: " + person.getBirthday());
Log.i(TAG, "Current Location: " + person.getCurrentLocation());
Log.i(TAG, "Language: " + person.getLanguage());
}
}
Inside build.gradle
file
// Dependency for Google Sign-In
compile 'com.google.android.gms:play-services-auth:8.3.0'
compile 'com.google.android.gms:play-services-plus:8.3.0'
You can take a look at My GitHub sample project. Hope this helps!
Can you get profile like gender and d.o.b from google signin on a website?
People.get returns a person resource However birthday will only return if the user has it set to public in the sharing settings on their profile.
It doesnt matter what scope you have set. They have to have set it to public i believe there is a feature request for this from back when google+ was around.
The same goes for Gender by default a lot of the personal information is set to private a user would have to purposely go and set it to public so that you can see it in the api.
Retrieving Users Gender While Google SignIn using Firebase but not getting all users Gender?
The thing is that gender
should be explicitly shared by the user on his Google +
account. I suggest you to experiment by yourself.
- Go to this page https://developers.google.com/people/api/rest/v1/people/get
- Type
resourceName
=people/me
andpersonFields
=genders
- Do the request, most likely you'll get the response with only
resourceName
andetag
fields. - Now go to https://plus.google.com/u/0/me page, which will open your G+ page and open Account Settings. Or you can open https://aboutme.google.com/u/0/ page directly.
- Click on the icon next to your Gender. This is the visibility setting, so user can choose if he wants to make his gender public, private or share only with circles. I suggest you to try different visibility options and check how it changes response at the step #3.
TL;DR: There is Gender
visibility setting on G+, user may have chosen not to share his gender and there is no dedicated profile scope to request during auth for it. This setting is competely private.
How to get gender and birthday from Google provider using FirebaseAuth?
Firebase does not support that but you can do that by this way:
First you needed client_id and client_secret.
You can get these two from Firebase panel by following steps:
Authentication >> SIGN-IN METHOD. Click Google and expand Web SDK Configuration.
Gradle dependencies:
compile 'com.google.apis:google-api-services-people:v1-rev63-1.22.0'
Add following methods in your login activity.
private void setupGoogleAdditionalDetailsLogin() {
// 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()
.requestIdToken(GOOGLE_CLIENT_ID)
.requestServerAuthCode(GOOGLE_CLIENT_ID)
.requestScopes(new Scope("profile"))
.build();
// Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed: ");
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
public void googleAdditionalDetailsResult(Intent data) {
Log.d(TAG, "googleAdditionalDetailsResult: ");
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Signed in successfully
GoogleSignInAccount acct = result.getSignInAccount();
// execute AsyncTask to get data from Google People API
new GoogleAdditionalDetailsTask().execute(acct);
} else {
Log.d(TAG, "googleAdditionalDetailsResult: fail");
startHomeActivity();
}
}
private void startGoogleAdditionalRequest() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_GOOGLE);
}
Async task to get additional details
public class GoogleAdditionalDetailsTask extends AsyncTask<GoogleSignInAccount, Void, Person> {
@Override
protected Person doInBackground(GoogleSignInAccount... googleSignInAccounts) {
Person profile = null;
try {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
//Redirect URL for web based applications.
// Can be empty too.
String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
// Exchange auth code for access token
GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
httpTransport,
jsonFactory,
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
googleSignInAccounts[0].getServerAuthCode(),
redirectUrl
).execute();
GoogleCredential credential = new GoogleCredential.Builder()
.setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.build();
credential.setFromTokenResponse(tokenResponse);
People peopleService = new People.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(App.getInstance().getString(R.string.app_name))
.build();
// Get the user's profile
profile = peopleService.people().get("people/me").execute();
} catch (IOException e) {
Log.d(TAG, "doInBackground: " + e.getMessage());
e.printStackTrace();
}
return profile;
}
@Override
protected void onPostExecute(Person person) {
if (person != null) {
if (person.getGenders() != null && person.getGenders().size() > 0) {
profileGender = person.getGenders().get(0).getValue();
}
if (person.getBirthdays() != null && person.getBirthdays().get(0).size() > 0) {
// yyyy-MM-dd
Date dobDate = person.getBirthdays().get(0).getDate();
if (dobDate.getYear() != null) {
profileBirthday = dobDate.getYear() + "-" + dobDate.getMonth() + "-" + dobDate.getDay();
profileYearOfBirth = DateHelper.getYearFromGoogleDate(profileBirthday);
}
}
if (person.getBiographies() != null && person.getBiographies().size() > 0) {
profileAbout = person.getBiographies().get(0).getValue();
}
if (person.getCoverPhotos() != null && person.getCoverPhotos().size() > 0) {
profileCover = person.getCoverPhotos().get(0).getUrl();
}
Log.d(TAG, String.format("googleOnComplete: gender: %s, birthday: %s, about: %s, cover: %s", profileGender, profileBirthday, profileAbout, profileCover));
}
startHomeActivity();
}
}
Change you onActivityResult like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_GOOGLE) { // result for addition details request
googleAdditionalDetailsResult(data);
return;
} else if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) { //logged in with firebase
if (FirebaseAuth.getInstance().getCurrentUser().getProviders().get(0).equals("google.com")) {
// user logged in with google account using firebase ui
startGoogleAdditionalRequest();
} else {
// user logged in with google
startHomeActivity();
}
} else {
// handle error
}
}
Update: if code gives error
personFields mask is required
then use following code:
profile = peopleService.people().get("people/me"). setRequestMaskIncludeField("person.names,person.emailAddresses,person.genders,person.birthdays").execute();
Thanks @AbrahamGharyali.
Related Topics
How to Change Text Color of Simple List Item
Android Searchview Filter Listview
Android Listview Row Delete Animation
Changing Default Port (I.E. 5037) on Which Adb Server Runs
Error Inflating Class and Android.Support.V7.Widget.Cardview
Get Nfc Tag with Ndef Android Application Record (Aar)
Android -- How to Position View Off-Screen
Why Use Armeabi-V7A Code Over Armeabi Code
Adding Fling Gesture to an Image View - Android
Android Singleton with Global Context
Applying Colorfilter to Imageview with Shapeddrawable
Suppress/Block Broadcastreceiver in Another App
Android Saf (Storage Access Framework): Get Particular File Uri from Treeuri
Google Maps API V2 'Failed to Load Map. Could Not Contact Google Servers'
Android App Enable Nfc Only for One Activity