Click here to see your recently viewed pages and most viewed pages.
Hide
Google+ Platform for Android

Start integrating Google+ into your Android app

Before you can start integrating Google+ features in your own app, you must create a Google Developers Console project and initialize the GoogleApiClient within your app. The steps on this page do just that. The next steps then describe how to integrate Google+ features into your app.

You can try out the quick-start sample app if you would like to quickly experiment with features of the platform.

Prerequisites

The Google+ platform for Android has the following requirements:

  • A physical device to use for developing and testing because Google Play services can only be installed on an emulator with an AVD that runs Google APIs platform based on Android 4.2.2 or higher.
  • The latest version of the Android SDK, including the SDK Tools component. The SDK is available from the Android SDK Manager.
  • Your project to compile against Android 2.3 (Gingerbread) or higher.
  • Eclipse configured to use Java 1.6
  • The Google Play Services SDK:
    1. Launch Eclipse and select Window > Android SDK Manager or run android from the command line.
    2. Scroll to the bottom of the package list and select Extras > Google Play services. The package is downloaded to your computer and installed in your SDK environment at <android-sdk-folder>/extras/google/google_play_services.

Step 1: Enable the Google+ API

If you already ran the quick start, the following steps are similar; however, this time you will create a OAuth 2.0 client for your package rather than for the quick-start package.

To authenticate and communicate with the Google+ APIs, you must create a Google Developers Console project, enable the Google+ API, create an OAuth 2.0 Client ID, and register your digitally signed .apk file's public certificate:

  1. Go to the Google Developers Console .

    Note: Create a single project for the Android, iOS and web versions of your app.

  2. Click Create Project:
    1. In the Project name field, type in a name for your project.
    2. In the Project ID field, optionally type in a project ID for your project or use the one that the console has created for you. This ID must be unique world-wide.
  3. Click the Create button and wait for the project to be created. Note: There may be short delay of up to 30 seconds before the project is created. Once the project is created, the name you gave it appears at the top of the left sidebar.
  4. In the left sidebar, select APIs & auth (the APIs sub-item is automatically selected).
    1. Find the Google+ API and set its status to ON—notice that this action moves Google+ API to the top of the list; you can scroll up to see it.
    2. Enable any other APIs that your app requires.
  5. In the left sidebar, select Credentials.
    1. Click Create a new Client ID—the Create Client ID dialog box appears, as shown further below.
    2. Select Installed application for the application type.
    3. Select Android as the installed application type.
    4. Enter your Android app's package name . into the Package name field.
    5. In a terminal, run the the Keytool utility to get the SHA-1 fingerprint of the certificate. For the debug.keystore, the password is android.
      keytool -exportcert -alias androiddebugkey -keystore <path-to-debug-or-production-keystore> -list -v

      Keytool prints the fingerprint hash to the shell. For example:

      $ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
      Enter keystore password: Type "android" if using debug.keystore
      Alias name: androiddebugkey
      Creation date: Aug 27, 2012
      Entry type: PrivateKeyEntry
      Certificate chain length: 1
      Certificate[1]:
      Owner: CN=Android Debug, O=Android, C=US
      Issuer: CN=Android Debug, O=Android, C=US
      Serial number: 503bd581
      Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
      Certificate fingerprints:
         MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
         SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
         SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
         Signature algorithm name: SHA1withRSA
         Version: 3
      

      Copy the SHA1 fingerprint hash from your terminal. The example above highlights where to find it.

    6. Paste the SHA-1 fingerprint hash into the Signing certificate fingerprint field shown below.
    7. To activate interactive posts, enable the Deep Linking option.

      Shows options in the Create Client ID dialog box.

    8. Click the Create client ID button.

You are done enabling the Google+ API for your app.

Step 2: Configure your Eclipse project

Integrating Google+ features in your Android app requires configuring your Android project in Eclipse. You will import and reference the Google Play services library project and set up the Java build path and libraries.

  1. Launch Eclipse.
  2. Select File > Import > Android > Existing Android Code Into Workspace and click Next.
  3. Select Browse.... Enter <android-sdk-folder>/extras/google/google_play_services/libproject. Displays the
  Eclipse import project dialog showing the options to import the library
  project
  4. Update the your project's properties:
    1. Click Project > Properties. The project properties dialog displays.
    2. Select Android, and in the Library section, click Add. Choose the google-play-services_lib project.
      Screenshot that shows the google-play-services_lib project correctly
   referenced as a library.
    3. Select Java Build Path, and click the Order and Export tab, select Android Private Libraries.
      Screenshot
    that shows the exported libraries for the project.
    4. Click OK.
  5. Optional: Click Project > Clean to ensure your project picks up the settings.

Step 3: Declare permissions

In your AndroidManifest.xml, you must add a meta-data tag as a child of the application tag to declare the version of Google Play services you are using.

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

You must also request the following permissions to use the noted features:

  • To access Google+ APIs:

    <uses-permission android:name="android.permission.INTERNET" />
    
  • To retrieve the account name (email) as part of sign-in:

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    
  • To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user. This disconnect option is required to comply with the Google+ Sign-In developer policies:

    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    

Step 4: Initialize the GoogleApiClient

The GoogleApiClient object wraps a ServiceConnection to Google Play services; this GoogleApiClient object is used to communicate with the Google+ API and becomes functional after the asynchronous connection has been established with the service, indicating that:

  • Google Play services is running on the device and your Activity has successfully bound the service connection,
  • the user has selected an account that they wish to use with your app, and
  • the user's account has granted the permissions that your app is requesting.

Typically, you want to manage the GoogleApiClient lifecycle in your activity's lifecycle:

  1. Initialize the GoogleApiClient object in your Activity.onCreate handler.
  2. Invoke GoogleApiClient.connect during Activity.onStart .
  3. Invoke GoogleApiClient.disconnect during Activity.onStop .

Your activity will listen for when the connection has established or failed by implementing the ConnectionCallbacks and OnConnectionFailedListener interfaces.

The addScope method shown below allows you to specify your app's initial scopes. Choose a login scope based on this criterion:

  • If you need access to the user's identity, social graph and the ability to write app activities, set the scope to PLUS_LOGIN.
  • If you just need access to basic profile information, set the scope to profile.

Your app can request additional scopes along with the login scope or request them anytime after the initial scopes have been granted. See Requesting additional scopes.

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;

public class ExampleActivity extends Activity implements
      ConnectionCallbacks, OnConnectionFailedListener {

  /* Request code used to invoke sign in user interactions. */
  private static final int RC_SIGN_IN = 0;

  /* Client used to interact with Google APIs. */
  private GoogleApiClient mGoogleApiClient;

  /* A flag indicating that a PendingIntent is in progress and prevents
   * us from starting further intents.
   */
  private boolean mIntentInProgress;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(Plus.API)
        .addScope(Plus.SCOPE_PLUS_LOGIN)
        .build();
  }

  protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
  }

  protected void onStop() {
    super.onStop();

    if (mGoogleApiClient.isConnected()) {
      mGoogleApiClient.disconnect();
    }
  }

  ...
}

When the GoogleApiClient object is unable to establish a connection, your implementation is notified of the failure in the onConnectionFailed callback, where you are passed a ConnectionResult that can be used to resolve the error. You can call ConnectionResult.getResolution() to retrieve a PendingIntent which, when sent, will allow Google Play services to solicit any user interaction needed to resolve sign in errors (for example by asking the user to select an account, consent to permissions, enable networking, etc).

public void onConnectionFailed(ConnectionResult result) {
  if (!mIntentInProgress && result.hasResolution()) {
    try {
      mIntentInProgress = true;
      startIntentSenderForResult(result.getResolution().getIntentSender(),
          RC_SIGN_IN, null, 0, 0, 0);
    } catch (SendIntentException e) {
      // The intent was canceled before it was sent.  Return to the default
      // state and attempt to connect to get an updated ConnectionResult.
      mIntentInProgress = false;
      mGoogleApiClient.connect();
    }
  }
}

public void onConnected(Bundle connectionHint) {
  // We've resolved any connection errors.  mGoogleApiClient can be used to
  // access Google APIs on behalf of the user.
}

Because the resolution for the connection failure was started with startIntentSenderForResult and the code RC_SIGN_IN, we can capture the result inside Activity.onActivityResult.

protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
  if (requestCode == RC_SIGN_IN) {
    mIntentInProgress = false;

    if (!mGoogleApiClient.isConnecting()) {
      mGoogleApiClient.connect();
    }
  }
}

Since the client establishes a connection to a service, you want to make sure the GoogleApiClient.disconnect method is called when appropriate to ensure robustness.

Google Play services will trigger the onConnectionSuspended callback if our Activity loses its service connection. Typically you will want to attempt to reconnect when this happens in order to retrieve a new ConnectionResult that can be resolved by the user.

public void onConnectionSuspended(int cause) {
  mGoogleApiClient.connect();
}

Next steps

Now that you have added GoogleApiClient to your activity, you can integrate your choice of Google+ features to your app:

Frequently asked questions

How do I continue to support older platforms, such as Eclair (v2.0)?

Check system version at runtime, and only call GoogleApiClient if the version is Android 2.3 (Gingerbread) or higher.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
    // Make the call to GoogleApiClient
}
How do I check to see if the Google+ app is installed on the device?

The GooglePlusUtil#checkGooglePlusApp utility method returns GooglePlusUtil.SUCCESS if the Google+ app is installed. If the app is not installed, you can prompt the user to install the app with the GooglePlusUtil#getErrorDialog utility method.

int errorCode = GooglePlusUtil.checkGooglePlusApp(this);
if (errorCode != GooglePlusUtil.SUCCESS) {
  GooglePlusUtil.getErrorDialog(errorCode, this, 0).show();
}
How do I debug my Google+ integration?

By enabling logging, you can diagnose network issues when working with the Google APIs.

To enable logging, run the following command:

adb shell setprop log.tag.GooglePlusPlatform VERBOSE

To disable logging, run the following command:

adb shell setprop log.tag.GooglePlusPlatform ""