Accessing Google APIs

When you want to make a call to one of the Google APIs provided in the Google Play services library (such as Google Sign-in and Drive), you need to create an instance of one the API client objects, which are subclasses of GoogleApi. These objects automatically manage the connection to Google Play services, queueing requests when offline, and executing them in order when a connection is available. GoogleApi objects are also cheap to create, so you can instantiate them as needed to access Google services.

This guide shows how you can make API calls to any of the Google Play services. Some services require the user to be signed in to their Google Account, and to have granted your app permission to access the service on their behalf.

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

Accessing Google services

To access a service that doesn't require API authorization, get an instance of the service's client object, passing it either the current Context or current Activity. If you pass an Activity, users will be prompted to upgrade or install Google Play services when necessary.

For example, to get the device's last known location using the fused location service:

FusedLocationClient client = LocationServices.getFusedLocationProviderClient(this);

// Get the last known location
client.getLastLocation()
        .addOnCompleteListener(this, new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                // ...
            }
        });

Accessing Google services that require authorization

To access a service that requires user authorization, first sign the user in, and request permission to access the scopes required by the service. Then, get an instance of the service's client object, passing it the user's GoogleSignInAccount object in addition to a Context or Activity.

For example, to access app files in a user's Drive:

// This account must have the necessary scopes to make the API call
// See https://developers.google.com/identity/sign-in/android/
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

// Get the app's Drive folder
DriveResourceClient client = Drive.getDriveResourceClient(this, account);
client.getAppFolder().
        .addOnCompleteListener(this, new OnCompleteListener<DriveFolder>() {
            @Override
            public void onComplete(@NonNull Task<DriveFolder>() {
                // ...
            }
        });