I am having trouble with the Google Plus Android API. I have a new activity, and I want to access the User's name and other details. How do I do that? I understand how to do it in the Sign In activity, but how do I access user information in this new activity?
Thanks in advance.
From the documentation on signing in:
When the user has successfully signed in, your onConnected handler will be called. At this point, you are able to retrieve the user’s account name or make authenticated requests.
It looks like there's a specific method for retrieving the signed-in user's information once sign in has been completed: Plus.PeopleApi.getCurrentPerson
Use the Plus.PeopleApi.getCurrentPerson method to request profile information the currently signed in user.
You can call the getCurrentPerson method after the GoogleApiClient is connected:
#Override
public void onConnected() {
...
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhoto = currentPerson.getImage();
String personGooglePlusProfile = currentPerson.getUrl();
}
}
Related
as Google+ stated here https://developers.google.com/+/mobile/android/people#retrieve_profile_information_for_a_signed_in_user
You can use the Plus.AccountApi.getAccountName method to get the user's email address that is associated with the connected account. You must declare the permission in your AndroidManifest.xml to use this method.
to get user email after login you have to write this code
final String email = Plus.AccountApi.getAccountName(googleApiClient);
end most important write GET_CONTACTS Permission on your AndroidManifest file.
but when I try same scenario on UBER app I noticed that they don't ask about GET_CONTACTS Permission and also get user email as I see it on UBER Settings screen
How I can get user Google+ email without asking user for GET_CONTACTS Permission.
You can get the user iformation from Google API using the following code.For more details you can refer : https://developers.google.com/identity/sign-in/android/people#before_you_begin
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
I"ve read this question on SO, but im still not clear how i would authenticate a user after a successful google signIn. I have an idea and im looking for approval from you. After a successful google signIn i will have access to the GoogleSignInAccount object. In this object i can do something like store the token and users email as the credentials into a remote db so i can recognize the users profile on my servers end. This could look something like this from android client side:
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
//now that i have an account lets store the token
String loginToken=acct.getIdToken();
storeTokenInRemoteDb(acct.getEmail(),loginToken);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
Is this the best practice to authenticate after good signIn success ?
For me I send the token to my server and then I validate it in the server side with sending request to
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=YOUR_TOKEN
That will return something like this if the token is still valid
{
"audience":"8819981768.apps.googleusercontent.com",
"user_id":"123456789",
"scope":"profile email",
"expires_in":436
}
And then I will also store the token locally in case the user logged out from my app and try to re-login with same google id and the token is still valid.
Use below code to access data such as name,emails etc
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
final String name = acct.getDisplayName();
final String email = acct.getEmail();
signOut();
if (name.contains(" ")) {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) == ' ') {
firstName = name.substring(0, i);
lastName = name.substring((i + 1),
name.length());
break;
}
}
}
I wanted to add something. The email address should not be used as the primary key for your local or webserver storage after authenticating the google account. You should use the account ID as user can have multiple email accounts but will alwyas have the same account ID.
So you could do it like this:
String accountName=Plus.AccountApi.getAccountName(mGoogleApiClient);
String accountID = GoogleAuthUtil.getAccountId(accountName);
now that we have the accountID we can go ahead and use it as as the primary key in any database locally or on a webserver. How else can you handle multiple email accounts ?Or what if user changed the primary email address.
some more info is here
The other thing i wanted to mention is that a hacker could attack your server by just keep guessing the email address of the user, so i would not base it on email address. I would use a token. After i get a token from the google sign in process i would let the android client upload the token to my server but then i would let the server speak to google servers to again verify the email address with this token and verify the token itself.
Am trying to display the profile picture of users logged into my app through Google+ but am not sure how to do this.To get the image (and other information), google provides the code
#Override
public void onConnected() {
...
if (mPlusClient.getCurrentPerson() != null) {
Person currentPerson = mPlusClient.getCurrentPerson();
String personName = currentPerson.getDisplayName();
String personPhoto = currentPerson.getImage();
String personGooglePlusProfile = currentPerson.getUrl();
}
}
I am aware that ordinarily i would need to get any image i want to display from res/drawable... but i don't know what to do with the value of personPhoto (which somehow get's changed from type String to Image when you paste the code in Eclipse.
You need to use that URL to grab the photo as a bitmap and set it to an imageview.
Section 4.9 of this article explains how to make an asynctask that will do just that:
http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
First you need to add this dependency in your app/build.gradle file:
dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
After this update your UI Accordingly :
private void updateUI(GoogleSignInAccount account) {
if (account != null){
text.setText("Sign in as :" +account.getDisplayName());
email.setText(account.getEmail());
String imgurl = account.getPhotoUrl().toString();
Glide.with(this).load(imgurl).into(profile);
sighIn.setVisibility(View.GONE);
sighOut.setVisibility(View.VISIBLE);
}
else {
text.setText("signOut");
sighIn.setVisibility(View.VISIBLE);
sighOut.setVisibility(View.GONE);
}
}
This is the solution that worked on my Android app. I developed it from an answer above by Naveen Kumar Yadav.
Prerequisites
- I am using a Google Sign-In API for my login.
- I have an XML Code with an ImageView that has an id "client_dp"
Add this dependency to your app-level build.gradle file
dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
Then add this code to your activity java file
//Firebase get user info
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser account = firebaseAuth.getCurrentUser();
if (account != null){
//Display User Image from Google Account
//Objects.requireNonNull() prevents getPhotoUrl() from returning a NullPointerException
String personImage = Objects.requireNonNull(account.getPhotoUrl()).toString();
ImageView userImage = findViewById(R.id.client_dp);
Glide.with(this).load(personImage).into(userImage);
}
With new google sign in Options in Kotlin. Simply request for the parameters you need in your onCreate function
val gso =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString("your-client-id"))
.requestEmail()
.requestProfile()
.requestId()
.build()
When recieving back the response from google Sign in activity, inside the
Get user profile picture through:
val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
val photoUrl = credential.photoUrl.toString()
I tried this example from google to authenticate with Google Drive and it can work. But the problem is that I don't know how to restore the previous success login from users. For example, when users login success, the next time they go to my app, they don't need to login again. I look in the GoogleAccountCredential class, it only have getToken method and don't have 'setToken` so I don't know how to do. And the document doesn't say anything about it. Here is my try:
credential = GoogleAccountCredential.usingOAuth2(context, DriveScopes.DRIVE);
// try to add login account into credential
String accountName = SharePreferenceHelper.getDriveAccount(context);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
}
// try to get token again
try {
String token = credential.getToken();
Log.d(TAG,"token = " + token);
} catch (UserRecoverableAuthException ex) {
startActivityForResult(ex.getIntent(), requestCode);
}
Does anybody know how to do it?
You need not do this manually. It is already taken care of by GoogleAccountCredential
This call
credential = GoogleAccountCredential.usingOAuth2(this, scopes);
will automatically restore the saved token if its previously saved.
You can check out a sample source code of my app here:
https://github.com/madhur/GAnalytics/blob/develop/src/in/co/madhur/ganalyticsdashclock/MainActivity.java
the difference it uses Google Analytics instead of Google Drive.
Hi I am trying to use the Parse Api's database for my project which requires user accounts that Parse provides. While I was reading the tutorial on how to set up user accounts at
https://parse.com/docs/android_guide#users it stated:
"Enabling email verification in an application's settings allows the application to reserve part of its experience for users with confirmed email addresses. Email verification adds the emailVerified key to the ParseUser object. When a ParseUser's email is set or modified, emailVerified is set to false. Parse then emails the user a link which will set emailVerified to true."
How exactly would you add the emailVerification key = true whenever a user tries to register:
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// sign up succeeded so go to multiplayer screen
// store the username of the current player
currentUser = username;
final String title = "Account Created Successfully!";
final String message = "Please verify your email before playing";
buildAlertDialog(title, message, true);
} else {
// sign up didnt succed. //TODO: figure out how do deal with error
final String title = "Error Account Creation failed";
final String message = "Account could not be created";
buildAlertDialog(title, message, false);
}
}
});
Go to your parse.com dashboard, go to settings, email settings and switch on the Verify user emails.
No code required.