Google+ Platform for Android

Getting people and profile information

After you have signed in a user with Google, you can access the user's age range, language, public profile information, and people that they have circled. If you request the plus.profile.emails.read scope, you can also get their email address. With this rich social data, you can build engaging experiences and an instant community in your app. For example, you might connect your user with their friends that also use your app or you might make suggestions based on their friends' activities within your app.

Before you begin

Create a Google APIs Console project and initialize the GoogleApiClient object as instructed at Getting Started with Android.

Retrieve the list of visible people in the user's circles

Use the Plus.PeopleApi.loadVisible method to make an asynchronous request to get a list of people who this user has added to one or more circles. The loadVisible method returns a list of people that are visible to the requesting app, which is the people who are in circles that the user has permitted the app to see. This list does not include names of circles.

The PersonBuffer offers a cursor-like interface for traversing through the collection of people. You must invoke the PersonBuffer.close method when you are done loading data from the PersonBuffer. The PersonBuffer.copyPerson method returns a new Person object based on the buffer's current position.

  1. Make the loadVisiblePeople request after the GoogleApiClient is connected.

    @Override
    public void onConnected() {
      ...
      Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
          .setResultCallback(this);
    }
    
  2. Have your activity implement the interface ResultCallback<People.LoadPeopleResult>.

    public class MyActivity extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener, ResultCallback<People.LoadPeopleResult> {
      ...
    }
    
  3. Handle the onResult callback.

    @Override
    public void onResult(LoadPeopleResult peopleData) {
      if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
        PersonBuffer personBuffer = peopleData.getPersonBuffer();
        try {
          int count = personBuffer.getCount();
          for (int i = 0; i < count; i++) {
            Log.d(TAG, "Display name: " + personBuffer.get(i).getDisplayName());
          }
        } finally {
          personBuffer.close();
        }
      } else {
        Log.e(TAG, "Error requesting visible circles: " + peopleData.getStatus());
      }
    }
    

The Plus.PeopleApi.loadVisible method is a native API binding around the people.list API and is a helper method for the Plus.PeopleApi.load method, which allows for finer control over retrieving collections of profiles to load.

Retrieve a collection of people

Use the Plus.PeopleApi.load method to make an asynchronous request to get a list of people specified by a list of user IDs. The PersonBuffer offers a cursor-like interface for traversing through the collection of people. You must invoke the PersonBuffer.close method when you are done loading data from the PersonBuffer. The PersonBuffer.copyPerson method returns a new Person object based on the buffer's current position.

  1. Make the load request after the GoogleApiClient is connected. You can call the load method with an array of user IDs in either their numeric format or their custom ID. For example:

    @Override
    public void onConnected() {
      ...
      List<String> userIds = new ArrayList<String>();
      userIds.add("107117483540235115863");
      userIds.add("+LarryPage");
      Plus.PeopleApi.load(mGoogleApiClient, userIds).setResultCallback(this);
    }
    
  2. Have your activity implement the interface ResultCallback<People.LoadPeopleResult>.

    public class MyActivity extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener, ResultCallback<People.LoadPeopleResult> {
      ...
    }
    
  3. Handle the onResult callback.

    @Override
    public void onResult(LoadPeopleResult peopleData) {
      if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
        PersonBuffer personBuffer = peopleData.getPersonBuffer();
        try {
          int count = personBuffer.getCount();
          for (int i = 0; i < count; i++) {
            Log.d(TAG, "Display name: " + personBuffer.get(i).getDisplayName());
          }
        } finally {
          personBuffer.close();
        }
      } else {
        Log.e(TAG, "Error requesting people data: " + peopleData.getStatus());
      }
    }
    

See the loadVisible method for a helper method to get a list of people in the authenticated user's circles.

Retrieve profile information for a signed in user

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

For additional profile data that might be available, see com.google.android.gms.plus.model.people.Person

The Plus.PeopleApi.getCurrentPerson method is a native API binding around the people.get API with the special "me" value provided as the user ID.

Retrieve an authenticated user's email address

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 <uses-permission android:name="android.permission.GET_ACCOUNTS" /> in your AndroidManifest.xml to use this method.

You can retrieve the user's email address in two ways:

  • You can call get the value of getAccountName(), which will return the email address that is associated with the account on the mobile device:

    String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
    
  • You can look up the address using the plus.profile.emails.read scope and REST end point to get the user's Google email account. The following example looks up and returns the email address asynchronously:

    class UserInfo {
      String id;
      String email;
      String verified_email;
    }
    
    final String account = Plus.AccountApi.getAccountName(mGoogleApiClient);
    
    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
    
      @Override
      protected UserInfo doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
    
        try {
          URL url = new URL("https://www.googleapis.com/plus/v1/people/me");
          String sAccessToken = GoogleAuthUtil.getToken(EmailTest.this, account,
            "oauth2:" + Scopes.PLUS_LOGIN + " https://www.googleapis.com/auth/plus.profile.emails.read");
    
          urlConnection = (HttpURLConnection) url.openConnection();
          urlConnection.setRequestProperty("Authorization", "Bearer " + sAccessToken);
    
          String content = CharStreams.toString(new InputStreamReader(urlConnection.getInputStream(),
              Charsets.UTF_8));
    
          if (!TextUtils.isEmpty(content)) {
            JSONArray emailArray =  new JSONObject(content).getJSONArray("emails");
    
            for (int i = 0; i < emailArray.length; i++) {
              JSONObject obj = (JSONObject)emailArray.get(i);
    
              // Find and return the primary email associated with the account
              if (obj.getString("type") == "account") {
                return obj.getString("value");
              }
            }
          }
        } catch (UserRecoverableAuthException userAuthEx) {
          // Start the user recoverable action using the intent returned by
          // getIntent()
          startActivityForResult(userAuthEx.getIntent(), RC_SIGN_IN);
          return;
       } catch (Exception e) {
          // Handle error
          // e.printStackTrace(); // Uncomment if needed during debugging.
        } finally {
          if (urlConnection != null) {
            urlConnection.disconnect();
          }
        }
    
        return null;
      }
    
      @Override
      protected void onPostExecute(String info) {
          // Store or use the user's email address
      }
    
    };
    
    task.execute();
    

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.