Access Google APIs - Google Play Services - Google For Developers

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Access Google APIs

When you want to make a call to one of the APIs in an SDK that's powered by Google
Play services, such as Google Sign-in or ML Kit, you need to first create an instance of
an API client object. These objects automatically manage the connection to Google
Play services. When a connection is available, each API client object executes
requests in order. Otherwise, the client object queues the requests. Unless
documentation indicates otherwise, client objects are cheap to construct; it's fine to
make new API clients every time you want to invoke API methods.

This guide shows how you can make API calls to any of the SDKs that are powered by
Google Play services, including how to access the services that don't require
authorization (#auth-not-required) and those that require authorization (#auth-required).

Get started
To get started, add the necessary tools and dependencies in your app project, as
described in the guide on how to set up Google Play services (/android/guides/setup).

Access when authorization isn't required


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
(https://developer.android.com/reference/android/content/Context) or the current Activity
(https://developer.android.com/reference/android/app/Activity). Before any API calls are
executed, users are prompted to upgrade Google Play services if necessary.

For example, to get the device's last known location using the Fused Location Provider
for Android, add the logic that's shown in the following code snippet:

KotlinJava (#java)
(#kotlin)

// Code required for requesting location permissions (https://developer.an


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

Access when authorization is required


To access a service that requires user authorization, complete the following steps:

1. Sign the user in (/identity/sign-in/android).

2. Request permission to access the scopes


(/identity/sign-in/android/additional-scopes) that the service requires.

3. Get an instance of the service's client object, passing it the user's


GoogleSignInAccount
(/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount)
object in addition to a Context
(https://developer.android.com/reference/android/content/Context) or Activity
(https://developer.android.com/reference/android/app/Activity) object.

The following example implements reading a user's daily steps using the Google Fit
API. To view a similar implementation in the context of a full project, view the main
activity of the BasicHistoryApiKotlin
(https://github.com/android/fit-
samples/blob/main/BasicHistoryApiKotlin/app/src/main/java/com/google/android/gms/fit/sam
ples/basichistoryapikotlin/MainActivity.kt)
app on GitHub.

KotlinJava (#java)
(#kotlin)

class FitFragment : Fragment() {


private val fitnessOptions: FitnessOptions by lazy {
FitnessOptions.builder()
.addDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
.addDataType(DataType.TYPE_STEP_COUNT_DELTA)
.build()
}

override fun onViewCreated(view: View, savedInstanceState: Bundl


fitSignIn()
}

/*
* Checks whether the user is signed in. If so, executes the spe
* function. If the user is not signed in, initiates the sign-in
* specifying the function to execute after the user signs in.
*/
private fun fitSignIn() {
if (oAuthPermissionsApproved()) {
readDailySteps()
} else {
GoogleSignIn.requestPermissions(
this,
SIGN_IN_REQUEST_CODE,
getGoogleAccount(),
fitnessOptions
)
}
}

private fun oAuthPermissionsApproved() =


GoogleSignIn.hasPermissions(getGoogleAccount(), fitnessOptio

/*
* Gets a Google account for use in creating the fitness client.
* achieved by either using the last signed-in account, or if ne
* prompting the user to sign in. It's better to use the
* getAccountForExtension() method instead of the getLastSignedI
* method because the latter can return null if there has been n
* before.
*/
private fun getGoogleAccount(): GoogleSignInAccount =
GoogleSignIn.getAccountForExtension(requireContext(), fitnes

/*
* Handles the callback from the OAuth sign in flow, executing t
* after sign-in is complete.
*/
override fun onActivityResult(
requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (resultCode) {
RESULT_OK -> {
readDailySteps()
}
else -> {
// Handle error.
}
}
}

/*
* Reads the current daily step total.
*/
private fun readDailySteps() {
Fitness.getHistoryClient(requireContext(), getGoogleAccount(
.readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA)
.addOnSuccessListener { dataSet ->
val total = when {
dataSet.isEmpty -> 0
else -> dataSet.dataPoints.first()
.getValue(Field.FIELD_STEPS).asInt()
}

Log.i(TAG, "Total steps: $total")


}
.addOnFailureListener { e ->
Log.w(TAG, "There was a problem getting the step cou
}
}

companion object {
const val SIGN_IN_REQUEST_CODE = 1001
}
}

Check for API availability


Before you enable a feature in your app that depends on a Google Play services API,
include a check for the availability of the API on the device. To do so, call
checkApiAvailability()
(/android/reference/com/google/android/gms/common/GoogleApiAvailability#checkApiAvailabil
ity(com.google.android.gms.common.api.HasApiKey%3C?
%3E,%20com.google.android.gms.common.api.HasApiKey%3C?%3E...))
.

Note: This check is only necessary if you need to disable a feature in your app when an API is
unavailable. It's also fine to call API methods without performing this check first because the API
calls fail if the API is unavailable.

The following code snippet demonstrates how to check for the availability of the fused
location provider.

KotlinJava (#java)
(#kotlin)

fun getLastLocationIfApiAvailable(context: Context?): Task<Location>


val client = getFusedLocationProviderClient(context)
return GoogleApiAvailability.getInstance()
.checkApiAvailability(client)
.onSuccessTask { _ -> client.lastLocation }
.addOnFailureListener { _ -> Log.d(TAG, "Location unavailabl
}

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution
4.0 License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the
Apache 2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google
Developers Site Policies (https://developers.google.com/site-policies). Java is a registered trademark
of Oracle and/or its affiliates.

Last updated 2024-06-05 UTC.

You might also like