Google+ Platform for Android

Getting Started with the Google+ Platform for Android

Before you can start integrating Google+ features in your own app, you must create a Google APIs Console project and initialize the GoogleApiClient within your app. You can try out the quick-start sample application if you would like to quickly experiment with 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 first register your digitally signed .apk file's public certificate in the Google APIs Console:

  1. In the Google APIs Console , create an API project for your application.
  2. In the Services pane, enable the Google+ API and any other APIs that your app requires.
  3. In the API Access pane, create an OAuth 2.0 client ID by clicking Create an OAuth 2.0 Client ID :
    1. Type a product name in the dialog box that displays, and click Next. Providing a product logo and home page URL are optional.
    2. Choose Installed application as your Application type and select Android as type.
    3. In the Package name field, enter your Android's app's package name.
    4. 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

      The Keytool prints the fingerprint 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 hash, which is highlighted in the example above.

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

      Shows options in the Create Client ID dialog box.

    7. Click the Create client ID button.

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](http://developer.android.com/reference/android/content/ServiceConnection.html) to Google Play services and is used to communicate with the Google+ API. The GoogleApiClient 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 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:

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, null)
        .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.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 ""

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.