Access Google APIs

To access APIs powered by Google Play services in your Android app, you need to use API client objects. These objects handle the connection to Google Play services, queueing requests and executing them in order when a connection is available. You can create new API clients as needed, as they are inexpensive to construct.

Get started

Before you begin, make sure to set up Google Play services in your app project.

To access a service that doesn't require authorization, create an instance of the service's client object, passing either a Context or an Activity object. If necessary, users are prompted to upgrade Google Play services before any API calls are executed.

The following code snippet shows how to get the device's last known location using the Fused Location Provider:

Kotlin

// Code required for requesting location permissions omitted for brevity.
val client = LocationServices.getFusedLocationProviderClient(this)

// Get the last known location. In some rare situations, this can be null.
client.lastLocation.addOnSuccessListener { location : Location? ->
    location?.let {
        // Logic to handle location object.
    }
}

Java

// Code required for requesting location permissions omitted for brevity.
FusedLocationProviderClient client =
        LocationServices.getFusedLocationProviderClient(this);

// Get the last known location. In some rare situations, this can be null.
client.getLastLocation()
        .addOnSuccessListener(this, location -> {
            if (location != null) {
                // Logic to handle location object.
            }
        });

To access APIs that require user authorization, follow the guide to authorize access to Google user data. If you are using an API that requires a GoogleSignInAccount object, use the AuthorizationResult#toGoogleSignInAccount() method.

Check for API availability

Before enabling a feature that depends on a Google Play services API, check if the API is available on the device by calling checkApiAvailability().

The following code snippet shows how to check if the fused location provider is available:

Kotlin

fun getLastLocationIfApiAvailable(context: Context?): Task<Location>? {
    val client = getFusedLocationProviderClient(context)
    return GoogleApiAvailability.getInstance()
        .checkApiAvailability(client)
        .onSuccessTask { _ -> client.lastLocation }
        .addOnFailureListener { _ -> Log.d(TAG, "Location unavailable.")}
}

Java

public Task<Location> getLastLocationIfApiAvailable(Context context) {
    FusedLocationProviderClient client =
            getFusedLocationProviderClient(context);
    return GoogleApiAvailability.getInstance()
            .checkApiAvailability(client)
            .onSuccessTask(unused -> client.getLastLocation())
            .addOnFailureListener(e -> Log.d(TAG, "Location unavailable."));
}