6

Mit Play Services 8.4 ist die Methode getCurrentPerson veraltet, und ich verwendete den PeopleApi, um den Vornamen, den Nachnamen und das Geschlecht des Benutzers zu erhalten.Plus.PeopleApi.getCurrentPerson in Play-Diensten als veraltet 8.4. Wie erhält man mit GoogleSignInApi den Vornamen, den Nachnamen und das Geschlecht des Nutzers?

Kann mir jemand sagen, wie man die angemeldeten Benutzerinformationen mit einer anderen Methode bekommt?

+0

Haben Sie versucht, [GoogleSignInResult] (https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInResult) zu verwenden? – gerardnimo

+0

Das einzige Objekt, das Daten über den Benutzer in GoogleSignInResult enthält, ist GoogleSignInAccount, das nicht die Daten enthält, die ich brauche. –

+0

Ich fand dieses alte [thread] (http://stackoverflow.com/questions/2108537/which-google-api-to-use-for-getting-users-first-name-last-name-bild-etc). Ich hoffe, das wird helfen. – gerardnimo

Antwort

9

Google Sign-In API kann Ihnen bereits mit ersten/letzten/Anzeigenamen, E-Mail und Profilbild URL.Wenn Sie andere Profilinformationen wie Geschlecht benötigen, verwenden Sie es in Verbindung mit neuen People API

// Add dependencies 
compile 'com.google.api-client:google-api-client:1.22.0' 
compile 'com.google.api-client:google-api-client-android:1.22.0' 
compile 'com.google.apis:google-api-services-people:v1-rev4-1.22.0' 

Dann schreiben Anmelde-Code,

// Make sure your GoogleSignInOptions request profile & email 
GoogleSignInOptions gso = 
     new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestEmail() 
      .build(); 
// Follow official doc to sign-in. 
// https://developers.google.com/identity/sign-in/android/sign-in 

Beim Umgang mit Anmelde-Ergebnis:

GoogleSignInResult result = 
     Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
if (result.isSuccess()) { 
    GoogleSignInAccount acct = result.getSignInAccount(); 
    String personName = acct.getDisplayName(); 
    String personGivenName = acct.getGivenName(); 
    String personFamilyName = acct.getFamilyName(); 
    String personEmail = acct.getEmail(); 
    String personId = acct.getId(); 
    Uri personPhoto = acct.getPhotoUrl(); 
} 

Verwenden Sie People Api, um detaillierte Personeninformationen abzurufen.

/** Global instance of the HTTP transport. */ 
private static HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport(); 
/** Global instance of the JSON factory. */ 
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 

// On worker thread 
GoogleAccountCredential credential = 
     GoogleAccountCredential.usingOAuth2(MainActivity.this, Scopes.PROFILE); 
credential.setSelectedAccount(new Account(personEmail, "com.google")); 
People service = new People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
       .setApplicationName(APPLICATION_NAME /* whatever you like */) 
       .build(); 
// All the person details 
Person meProfile = service.people().get("people/me").execute(); 
// e.g. Gender 
List<Gender> genders = meProfile.getGenders(); 
String gender = null; 
if (genders != null && genders.size() > 0) { 
    gender = genders.get(0).getValue(); 
} 

einen Blick auf JavaDoc nehmen, um zu sehen, was andere Profilinformationen Sie bekommen können.

10

Aktualisierung: Überprüfen Sie Isabellas Antwort. Diese Antwort verwendet veraltete Inhalte.

Ich fand die Lösung selbst, also poste ich es hier, wenn jemand anderes das gleiche Problem hat.

Obwohl ich nach einer Lösung für die Verwendung von GoogleSignInApi suchte, um Benutzerinformationen zu erhalten, konnte ich das nicht finden und ich denke, wir müssen die Plus-API verwenden, um Informationen wie Geschlecht zu erhalten.

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
      handleSignInResult(result); 
     } 
    } 

HandleSignInResult

private void handleSignInResult(GoogleSignInResult result) 
    { 
     Log.d(TAG, "handleSignInResult:" + result.isSuccess()); 
     if (result.isSuccess()) 
     { 
      GoogleSignInAccount acct = result.getSignInAccount(); 
      Toast.makeText(getApplicationContext(),""+acct.getDisplayName(),Toast.LENGTH_LONG).show(); 

      Plus.PeopleApi.load(mGoogleApiClient, acct.getId()).setResultCallback(new ResultCallback<People.LoadPeopleResult>() { 
       @Override 
       public void onResult(@NonNull People.LoadPeopleResult loadPeopleResult) { 
        Person person = loadPeopleResult.getPersonBuffer().get(0); 
        Log.d(TAG,"Person loaded"); 
        Log.d(TAG,"GivenName "+person.getName().getGivenName()); 
        Log.d(TAG,"FamilyName "+person.getName().getFamilyName()); 
        Log.d(TAG,("DisplayName "+person.getDisplayName())); 
        Log.d(TAG,"Gender "+person.getGender()); 
        Log.d(TAG,"Url "+person.getUrl()); 
        Log.d(TAG,"CurrentLocation "+person.getCurrentLocation()); 
        Log.d(TAG,"AboutMe "+person.getAboutMe()); 
        Log.d(TAG,"Birthday "+person.getBirthday()); 
        Log.d(TAG,"Image "+person.getImage()); 
       } 
      }); 

      //mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName())); 
      //updateUI(true); 
     } else { 
      //updateUI(false); 
     } 
    } 
+3

Plus.PeopleApi ist veraltet. Weitere Informationen finden Sie unter Anmerkungen zur Deaktivierung: https://developers.google.com/+/mobile/android/api-deprecation. Wenn Sie andere Profilinformationen als den ersten/letzten/angezeigten Namen, die E-Mail-Adresse und die Profilbild-URL (die bereits von GoogleSignInAccount bereitgestellt wird) erhalten möchten, verwenden Sie die neue People-REST-API. Siehe Codebeispiel in meiner Antwort unten. Vielen Dank! –

+0

@IsabellaChen Danke für den Link, Das Profilbild (URL) in GoogleSignInAccount ist sehr klein. Gibt es eine Möglichkeit, ein größeres Bild zu bekommen? Ich möchte kein unscharfes Bild des Benutzers auf meiner Benutzeroberfläche anzeigen. –

+1

Leider keine empfohlene Vorgehensweise in diesem Moment. 96 * 96 Foto wird gerade serviert. Die meisten Apps zeigen einfach ein Thumbnail an und diese Größe ist genug für sie. Wenn Sie sich eine Profilfoto-URL anschauen, sehen Sie, dass sie mit "s96-c/photo.jpg" endet, was in diesem Moment 96 * 96 bedeutet. Aber keine Garantie, dass sich das Schema in Zukunft nicht ändert. Daher empfehle ich nicht, die URL selbst zu ändern. –

2

Hallo Ich habe eine alternative Möglichkeit für die neueste Google Plus Login gefunden, verwenden das Verfahren unter:

GoogleApiClient mGoogleApiClient; 

private void latestGooglePlus() { 
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestProfile().requestEmail().requestScopes(Plus.SCOPE_PLUS_LOGIN, Plus.SCOPE_PLUS_PROFILE, new Scope("https://www.googleapis.com/auth/plus.profile.emails.read")) 
      .build(); 

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .enableAutoManage(this, this) 
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
      .addApi(Plus.API) 
      .build(); 

    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
    startActivityForResult(signInIntent, YOURREQUESTCODE); 
} 

Und auf Aktivität Ergebnis Verwendung der Code unten:

Schließlich Ihr onClick wird:

@Override 
public void onClick(View v) { 
    switch (v.getId()) { 

     case R.id.txtGooglePlus: 
      latestGooglePlus(); 
      break; 

     default: 
      break; 
    } 
} 
1

Gerade oben Hardy Antwort hinzuzufügen, die mich in die richtige Richtung geführt.

Ich endete mit zwei Anrufe an GoogleApiClient, wie ich nicht bekommen konnte, was Hardy oben zu arbeiten hat.

Mein erster Anruf ist auf den GoogleSignInApi

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestProfile() 
      .requestEmail() 
      .requestIdToken(MY_GOOGLE_SERVER_CLIENT_ID) 
      .build(); 

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
      .build(); 

    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
    startActivityForResult(signInIntent, ThinQStepsConstants.REQUEST_CODE_GOOGLE_SIGN_IN); 

Dieser dann geben Sie mir den ersten Teil durch die onActivityResult, die gleichen wie Hardy. Doch dann verwende ich den Anruf an die GoogleApiClient.Builder wieder

mGoogleApiClientPlus = new GoogleApiClient.Builder(getActivity()) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(Plus.API) 
      .addScope(Plus.SCOPE_PLUS_PROFILE) 
      .build(); 

mGoogleApiClientPlus.connect(); 

Jetzt kann ich die Plus.PeopleApi über den Rückruf onConnected Zugriff

@Override 
public void onConnected(Bundle connectionHint) { 
    Log.i(TAG, "onConnected"); 

    Plus.PeopleApi.load(mGoogleApiClientPlus, mGoogleId).setResultCallback(new ResultCallback<People.LoadPeopleResult>() { 
     @Override 
     public void onResult(@NonNull People.LoadPeopleResult loadPeopleResult) { 
      Person currentPerson = loadPeopleResult.getPersonBuffer().get(0); 
     } 
    }); 

} 

Mit entsprechenden trennt und widerruft.

Sie können feststellen, dass mein Code die gleichen Rückrufe verwendet, die ich aufräumen muss, aber der Auftraggeber ist da.

2

Das erste, was zu tun ist, folgen Sie der Google-Orientierung bei Add Google Sign-In to Your Android App.

Dann müssen Sie die GoogleSignInOptions ändern:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestIdToken(getString(R.string.default_web_client_id)) 
      .requestProfile() 
      .requestEmail() 
      .build(); 

Wenn Sie eine andere Bereiche hinzufügen, müssen Sie es wie folgt tun:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestIdToken(getString(R.string.default_web_client_id)) 
      .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER)) 
      .requestProfile() 
      .requestEmail() 
      .build(); 

Und 'onActivityResult' innen ‚if (result.isSuccess()) {‘einfügen this:

new requestUserInfoAsync(this /* Context */, acct).execute(); 

und dieses Verfahren erzeugen:

private static class requestUserInfoAsync extends AsyncTask<Void, Void, Void> { 

    // Global instance of the HTTP transport. 
    private static HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport(); 
    // Global instance of the JSON factory. 
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 

    private Context context; 
    private GoogleSignInAccount acct; 

    private String birthdayText; 
    private String addressText; 
    private String cover; 

    public requestUserInfoAsync(Context context, GoogleSignInAccount acct) { 
     this.context = context; 
     this.acct = acct; 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // On worker thread 
     GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
       context, Collections.singleton(Scopes.PROFILE) 
     ); 
     credential.setSelectedAccount(new Account(acct.getEmail(), "com.google")); 
     People service = new People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
       .setApplicationName(context.getString(R.string.app_name) /* whatever you like */) 
       .build(); 

     // All the person details 
     try { 
      Person meProfile = service.people().get("people/me").execute(); 

      List<Birthday> birthdays = meProfile.getBirthdays(); 
      if (birthdays != null && birthdays.size() > 0) { 
       Birthday birthday = birthdays.get(0); 

       // DateFormat.getDateInstance(DateFormat.FULL).format(birthdayDate) 
       birthdayText = ""; 
       try { 
        if (birthday.getDate().getYear() != null) { 
         birthdayText += birthday.getDate().getYear() + " "; 
        } 
        birthdayText += birthday.getDate().getMonth() + " " + birthday.getDate().getDay(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 

      List<Address> addresses = meProfile.getAddresses(); 
      if (addresses != null && addresses.size() > 0) { 
       Address address = addresses.get(0); 
       addressText = address.getFormattedValue(); 
      } 

      List<CoverPhoto> coverPhotos = meProfile.getCoverPhotos(); 
      if (coverPhotos != null && coverPhotos.size() > 0) { 
       CoverPhoto coverPhoto = coverPhotos.get(0); 
       cover = coverPhoto.getUrl(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 

     Log.i("TagTag", "birthday: " + birthdayText); 
     Log.i("TagTag", "address: " + addressText); 
     Log.i("TagTag", "cover: " + cover); 
    } 
} 

Mit diesem Sie die Methoden innerhalb ‚Person meProfile‘ können andere Informationen zu bekommen, aber Sie können das bekommen nur die öffentlichen Informationen des Benutzers sonst wird es null sein.

Verwandte Themen