Accessing Google APIs

When you want to make a connection to one of the Google APIs provided in the Google Play services library (such as Google Sign-In, Games, or Drive), you need to create an instance of GoogleApiClient ("Google API Client"). The Google API Client provides a common entry point to all the Google Play services and manages the network connection between the user's device and each Google service.

This guide shows how you can:

  • Automatically manage your connection to Google Play services.
  • Perform synchronous and asynchronous API calls to any of the Google Play services.
  • Manually manage your connection to Google Play services in those rare cases where this is necessary. To learn more, see Manually managed connections.

Note: If you have an existing app that connects to Google Play services with a subclass of GooglePlayServicesClient, you should migrate to GoogleApiClient as soon as possible.

Figure 1: An illustration showing how the Google API Client provides an interface for connecting and making calls to any of the available Google Play services such as Google Play Games and Google Drive.

To get started, you must first install the Google Play services library (revision 15 or higher) for your Android SDK. If you haven't done so already, follow the instructions in Set Up Google Play Services SDK.

Start an automatically managed connection

After your project is linked to the Google Play services library, create an instance of GoogleApiClient using the GoogleApiClient.Builder APIs in your activity's onCreate() method. The GoogleApiClient.Builder class provides methods that allow you to specify the Google APIs you want to use and your desired OAuth 2.0 scopes. Here is a code example that creates a GoogleApiClient instance that connects with the Google Drive service:

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this /* FragmentActivity */,
                      this /* OnConnectionFailedListener */)
    .addApi(Drive.API)
    .addScope(Drive.SCOPE_FILE)
    .build();

You can add multiple APIs and multiple scopes to the same GoogleApiClient by appending additional calls to addApi() and addScope().

Important: If you are adding the Wearable API together with other APIs to a GoogleApiClient, you may run into client connection errors on devices that do not have the Android Wear app installed. To avoid connection errors, call the addApiIfAvailable() method and pass in the Wearable API to allow your client to gracefully handle the missing API. For more information, see Access the Wearable API.

To begin an automatically managed connection, you must specify an implementation for the OnConnectionFailedListener interface to receive unresolvable connection errors. When your auto-managed GoogleApiClient instance attempts to connect to Google APIs, it will automatically display UI to attempt to fix any resolvable connection failures (for example, if Google Play services needs to be updated). If an error occurs that cannot be resolved, you will receive a call to onConnectionFailed().

You may also specify an optional implementation for the ConnectionCallbacks interface if your app needs to know when the automatically managed connection is established or suspended. For example if your app makes calls to write data to Google APIs, these should be invoked only after the onConnected() method has been called.

Here is an example activity that implements the callback interfaces and adds them to the Google API Client:

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import gms.drive.*;
import android.support.v4.app.FragmentActivity;

public class MyActivity extends FragmentActivity
        implements OnConnectionFailedListener {
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create a GoogleApiClient instance
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */,
                                  this /* OnConnectionFailedListener */)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .build();

        // ...
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // An unresolvable error has occurred and a connection to Google APIs
        // could not be established. Display an error message, or handle
        // the failure silently

        // ...
    }
}

Your GoogleApiClient instance will automatically connect after your activity calls onStart() and disconnect after calling onStop(). Your app can immediately begin making read requests to Google APIs after building GoogleApiClient, without waiting for the connection to complete.

Communicate with Google Services

After connecting, your client can make read and write calls using the service-specific APIs for which your app is authorized, as specified by the APIs and scopes you added to your GoogleApiClient instance.

Note: Before making calls to specific Google services, you may first need to register your app in the Google Developer Console. For instructions, refer to the appropriate getting started guide for the API you're using, such as Google Drive or Google Sign-In.

When you perform a read or write request using GoogleApiClient, the API client returns a PendingResult object that represents the request. This occurs immediately, before the request is delivered to the Google service that your app is calling.

For example, here's a request to read a file from Google Drive that provides a PendingResult object:

Query query = new Query.Builder()
        .addFilter(Filters.eq(SearchableField.TITLE, filename));
PendingResult<DriveApi.MetadataBufferResult> result = Drive.DriveApi.query(mGoogleApiClient, query);

After your app has a PendingResult object, your app can then specify whether the request is handled as an asynchronous call or as a synchronous call.

Tip: Your app can enqueue read requests while not connected to Google Play services. For example, your app can call methods to read a file from Google Drive regardless of whether your GoogleApiClient instance is connected yet. After a connection is established, enqueued read requests execute. Write requests generate an error if your app calls Google Play services write methods while your Google API Client is not connected.

Using asynchronous calls

To make the request asynchronous, call setResultCallback() on the PendingResult and provide an implementation of the ResultCallback interface. For example, here's the request executed asynchronously:

private void loadFile(String filename) {
    // Create a query for a specific filename in Drive.
    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, filename))
            .build();
    // Invoke the query asynchronously with a callback method
    Drive.DriveApi.query(mGoogleApiClient, query)
            .setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(DriveApi.MetadataBufferResult result) {
            // Success! Handle the query result.
            // ...
        }
    });
}

When your app receives a Result object in the onResult() callback, it is delivered as an instance of the appropriate subclass as specified by the API you're using, such as DriveApi.MetadataBufferResult.

Using synchronous calls

If you want your code to execute in a strictly defined order, perhaps because the result of one call is needed as an argument to another, you can make your request synchronous by calling await() on the PendingResult. This blocks the thread and returns the Result object when the request completes. This object is delivered as an instance of the appropriate subclass as specified by the API you're using, for example DriveApi.MetadataBufferResult.

Because calling await() blocks the thread until the result arrives, your app should never make synchronous requests to Google APIs on the UI thread. Your app can create a new thread using an AsyncTask object, and use that thread to make the synchronous request.

The following example shows how to make a file request to Google Drive as a synchronous call:

private void loadFile(String filename) {
    new GetFileTask().execute(filename);
}

private class GetFileTask extends AsyncTask {
    protected void doInBackground(String filename) {
        Query query = new Query.Builder()
                .addFilter(Filters.eq(SearchableField.TITLE, filename))
                .build();
        // Invoke the query synchronously
        DriveApi.MetadataBufferResult result =
                Drive.DriveApi.query(mGoogleApiClient, query).await();

        // Continue doing other stuff synchronously
        // ...
    }
}

Access the Wearable API

The Wearable API provides a communication channel for apps that run on handheld and wearable devices. The API consists of a set of data objects that the system can send and synchronize, and listeners that notify your apps of important events using a data layer. The Wearable API is available on devices running Android 4.3 (API level 18) or higher when a wearable device is connected and the Android Wear companion app is installed on the device.

Using the Wearable API stand-alone

If your app uses the Wearable API but not other Google APIs, you can add this API by calling the addApi() method. The following example shows how to add the Wearable API to your GoogleApiClient instance:

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this /* FragmentActivity */,
                      this /* OnConnectionFailedListener */)
    .addApi(Wearable.API)
    .build();

In situations where the Wearable API is not available, connection requests that include the Wearable API fail with the API_UNAVAILABLE error code.

The following example shows how to determine whether the Wearable API is available:

// Connection failed listener method for a client that only
// requests access to the Wearable API
@Override
public void onConnectionFailed(ConnectionResult result) {
    if (result.getErrorCode() == ConnectionResult.API_UNAVAILABLE) {
        // The Wearable API is unavailable
    }
    // ...
}

Using the Wearable API with other Google APIs

If your app uses the Wearable API in addition to other Google APIs, call the addApiIfAvailable() method and pass in the Wearable API to check whether it is available. You can use this check to help your app to gracefully handle cases where the API is unavailable.

The following example shows how to access the Wearable API along with the Drive API:

// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this /* FragmentActivity */,
                          this /* OnConnectionFailedListener */)
        .addApi(Drive.API)
        .addApiIfAvailable(Wearable.API)
        .addScope(Drive.SCOPE_FILE)
        .build();

In the example above, the GoogleApiClient can successfully connect with Google Drive without connecting to the Wearable API if it is unavailable. After you connect your GoogleApiClient instance, ensure that the Wearable API is available before making the API calls:

boolean wearAvailable = mGoogleApiClient.hasConnectedApi(Wearable.API);

Ignoring API Connection Failures

If you call addApi() and the GoogleApiClient is unable to connect successfully to that API, the entire connection operation for that client fails and triggers the onConnectionFailed() callback.

You can register an API connection failure to be ignored by using addApiIfAvailable(). If an API added with addApiIfAvailable() fails to connect due to a non-recoverable error (like API_UNAVAILABLE for Wear), that API is dropped from your GoogleApiClient and the client proceeds to connect to other APIs. However, if any API connection fails with a recoverable error (like an OAuth consent resolution intent), the client connect operation fails. When using an automatically managed connection the GoogleApiClient will attempt to resolve such errors when possible. When using a manually managed connection a ConnectionResult containing a resolution intent is delivered to the onConnectionFailed() callback. API connection failures are ignored only if there is no resolution for the failure and the API was added with addApiIfAvailable(). To learn how to implement manual connection failure handling, see Handle connection failures.

Because APIs added with addApiIfAvailable() may not always be present in the connected GoogleApiClient instance, you should guard calls to these APIs by adding a check using hasConnectedApi(). To find out why a particular API failed to connect when the entire connection operation succeeded for the client, call getConnectionResult() and get the error code from the ConnectionResult object. If your client calls an API when it is not connected to the client, the call fails with the API_NOT_AVAILABLE status code.

If the API you are adding through addApiIfAvailable() requires one or more scopes, add those scopes as parameters in your addApiIfAvailable() method call rather than by using the addScope() method. Scopes added using this approach may not be requested if the API connection fails before getting OAuth consent, whereas scopes added with addScope() are always requested.

Manually managed connections

The majority of this guide shows you how to use the enableAutoManage method to initiate an automatically managed connection with automatically resolved errors. In almost all cases, this is the best and easiest way to connect to Google APIs from your Android app. However, there are some situations where you would want to use a manually managed connection to Google APIs in your app:

  • To access Google APIs outside of an activity or retain control of the API connection
  • To customize connection error handling and resolution

This section provides examples of these and other advanced use cases.

Start a manually managed connection

To initiate a manually managed connection to GoogleApiClient, you must specify an implementation for the callback interfaces, ConnectionCallbacks and OnConnectionFailedListener. These interfaces receive callbacks in response to the asynchronous connect() method when the connection to Google Play services succeeds, fails, or becomes suspended.

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build()

When managing a connection manually you will need to call the connect() and disconnect() methods at the right points in your app's lifecycle. In an activity context the best practice is to call connect() in your activity's onStart() method and disconnect() in your activity's onStop() method. The connect() and disconnect() methods are called automatically when using an automatically managed connection.

If you are using GoogleApiClient to connect to APIs that require authentication, like Google Drive or Google Play Games, there's a good chance your first connection attempt will fail and your app will receive a call to onConnectionFailed() with the SIGN_IN_REQUIRED error because the user account was not specified.

Handle connection failures

When your app receives a call to the onConnectionFailed() callback, you should call hasResolution() on the provided ConnectionResult object. If it returns true, your app can request that the user take immediate action to resolve the error by calling startResolutionForResult() on the ConnectionResult object. The startResolutionForResult() method behaves the same as startActivityForResult() in this situation, and launches an activity appropriate to the context that helps the user to resolve the error (such as an activity that helps the user to select an account).

If hasResolution() returns false, your app should call GoogleApiAvailability.getErrorDialog(), passing the error code to this method. This returns a Dialog provided by Google Play services that's appropriate to the error. The dialog may simply provide a message explaining the error, or it may also provide an action to launch an activity that can resolve the error (such as when the user needs to install a newer version of Google Play services).

For example, your onConnectionFailed() callback method should now look like this:

public class MyActivity extends Activity
        implements ConnectionCallbacks, OnConnectionFailedListener {

    // Request code to use when launching the resolution activity
    private static final int REQUEST_RESOLVE_ERROR = 1001;
    // Unique tag for the error dialog fragment
    private static final String DIALOG_ERROR = "dialog_error";
    // Bool to track whether the app is already resolving an error
    private boolean mResolvingError = false;

    // ...

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (mResolvingError) {
            // Already attempting to resolve an error.
            return;
        } else if (result.hasResolution()) {
            try {
                mResolvingError = true;
                result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
            } catch (SendIntentException e) {
                // There was an error with the resolution intent. Try again.
                mGoogleApiClient.connect();
            }
        } else {
            // Show dialog using GoogleApiAvailability.getErrorDialog()
            showErrorDialog(result.getErrorCode());
            mResolvingError = true;
        }
    }

    // The rest of this code is all about building the error dialog

    /* Creates a dialog for an error message */
    private void showErrorDialog(int errorCode) {
        // Create a fragment for the error dialog
        ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
        // Pass the error that should be displayed
        Bundle args = new Bundle();
        args.putInt(DIALOG_ERROR, errorCode);
        dialogFragment.setArguments(args);
        dialogFragment.show(getSupportFragmentManager(), "errordialog");
    }

    /* Called from ErrorDialogFragment when the dialog is dismissed. */
    public void onDialogDismissed() {
        mResolvingError = false;
    }

    /* A fragment to display an error dialog */
    public static class ErrorDialogFragment extends DialogFragment {
        public ErrorDialogFragment() { }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Get the error code and retrieve the appropriate dialog
            int errorCode = this.getArguments().getInt(DIALOG_ERROR);
            return GoogleApiAvailability.getInstance().getErrorDialog(
                    this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            ((MyActivity) getActivity()).onDialogDismissed();
        }
    }
}

After the user completes the dialog provided by startResolutionForResult() or dismisses the message provided by GoogleApiAvailability.getErrorDialog(), your activity receives the onActivityResult() callback with the RESULT_OK result code. Your app can then call connect() again. For example:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_RESOLVE_ERROR) {
        mResolvingError = false;
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mGoogleApiClient.isConnecting() &&
                    !mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }
        }
    }
}

In the above code, you probably noticed the boolean, mResolvingError. This keeps track of the app state while the user is resolving the error to avoid repetitive attempts to resolve the same error. For example, while the account picker dialog is displayed to help the user to resolve the SIGN_IN_REQUIRED error, the user may rotate the screen. This recreates your activity and causes your onStart() method to be called again, which then calls connect() again. This results in another call to startResolutionForResult(), which creates another account picker dialog in front of the existing one.

This boolean serves its intended purpose only if it persists across activity instances. The next section explains how to maintain the error handling state of your app despite other user actions or events that occur on the device.

Maintain state while resolving an error

To avoid executing the code in onConnectionFailed() while a previous attempt to resolve an error is in progress, you need to retain a boolean that tracks whether your app is already attempting to resolve an error.

As shown in the code example above, your app should set a boolean to true each time it calls startResolutionForResult() or displays the dialog from GoogleApiAvailability.getErrorDialog(). Then, when your app receives RESULT_OK in the onActivityResult() callback, set the boolean to false.

To keep track of the boolean across activity restarts (such as when the user rotates the screen), save the boolean in the activity's saved instance data using onSaveInstanceState():

private static final String STATE_RESOLVING_ERROR = "resolving_error";

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}

Then recover the saved state during onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...
    mResolvingError = savedInstanceState != null
            && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
}

Now you're ready to safely run your app and manually connect to Google Play services.