Google api client android

Accessing Google APIs

In this document

When you want to make a connection to one of the Google APIs provided in the Google Play services library (such as Google+, 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.

Connecting to REST APIs

If the Google API you want to use is not included in the Google Play services library, you can connect using the appropriate REST API, but you must obtain an OAuth 2.0 token. For more information, read Authorizing with Google for REST APIs.

This guide shows how you can use Google API Client to:

  • Connect to one or more Google Play services asynchronously and handle failures.
  • Perform synchronous and asynchronous API calls to any of the Google Play services.

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 a Connection

Once 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. For example, here’s a GoogleApiClient instance that connects with the Google Drive service:

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 multiple 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 , com.google.android.gms.common.api.Scope. )»> addApiIfAvailable() method and pass in the Wearable API to indicate that your client should gracefully handle the missing API. For more information, see Access the Wearable API.

Before you can begin a connection by calling connect() on the 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.

For example, here’s an activity that implements the callback interfaces and adds them to the Google API Client:

With the callback interfaces defined, you’re ready to call connect() . To gracefully manage the lifecycle of the connection, you should call connect() during the activity’s onStart() (unless you want to connect later), then call disconnect() during the onStop() method. For example:

However, if you run this code, there’s a good chance it will fail and your app will receive a call to onConnectionFailed() with the SIGN_IN_REQUIRED error because the user account has not been specified. The next section shows how to handle this error and others.

Читайте также:  Platform tools android studio path

Handle connection failures

When you receive a call to the onConnectionFailed() callback, you should call hasResolution() on the provided ConnectionResult object. If it returns true, you can request the user take immediate action to resolve the error by calling startResolutionForResult() on the ConnectionResult object. The startResolutionForResult() behaves the same as startActivityForResult() and launches the appropriate activity for the user to resolve the error (such as an activity to select an account).

If hasResolution() returns false, you should instead call GooglePlayServicesUtil.getErrorDialog() , passing it the error code. This returns a Dialog provided by Google Play services that’s appropriate for the given error. The dialog may simply provide a message explaining the error, but 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:

Once the user completes the resolution provided by startResolutionForResult() or GooglePlayServicesUtil.getErrorDialog() , your activity receives the onActivityResult() callback with the RESULT_OK result code. You can then call connect() again. For example:

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 instance, while the account picker dialog is showing 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 is effective only if retained across activity instances, though. The next section explains further.

Maintain state while resolving an error

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

As shown in the code above, you should set a boolean to true each time you call startResolutionForResult() or display the dialog from GooglePlayServicesUtil.getErrorDialog() . Then when you receive 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() :

Then recover the saved state during onCreate() :

Now you’re ready to safely run your app and connect to Google Play services. How you can perform read and write requests to any of the Google Play services using GoogleApiClient is discussed in the next section.

For more information about each services’s APIs available once you’re connected, consult the corresponding documentation, such as for Google Play Games or Google Drive.

Access the Wearable API

The Wearable API provides a communication channel for your handheld and wearable apps. The API consists of a set of data objects that the system can send and synchronize over the wire and listeners that notify your apps of important events with the data layer. The Wearable API is available on devices running Android 4.3 (API level 18) or higher when a wearable device is connected. The API is not available under the following conditions:

  • Devices running Android 4.2 (API level 17) or earlier.
  • Android Wear companion app is not installed on the device.
  • Android Wear device is not connected.

Using only the Wearable API

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:

Читайте также:  Sdl error libpng16 so android

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:

Using the Wearable API with other APIs

If your app uses the Wearable API in addition to other Google APIs, call the , com.google.android.gms.common.api.Scope. )»>addApiIfAvailable() method and pass in the Wearable API to indicate that your client should gracefully handle the missing API.

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

In the example above, the GoogleApiClient can successfully connect with the Google Drive service 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:

Communicate with Google Services

Once connected, 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 specific instructions, refer to the appropriate getting started guide for the API you’re using, such as Google Drive or Google+.

When you perform a read or write request using Google API Client, the immediate result is returned as a PendingResult object. This is an object representing the request, which hasn’t yet been delivered to the Google service.

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

Once you have the PendingResult , you can continue by making the request either asynchronous or synchronous.

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:

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, which is delivered as an instance of the appropriate subclass as specified by the API you’re using, such as DriveApi.MetadataBufferResult .

Because calling await() blocks the thread until the result arrives, it’s important that you never perform this call on the UI thread. So, if you want to perform synchronous requests to a Google Play service, you should create a new thread, such as with AsyncTask in which to perform the request. For example, here’s how to perform the same file request to Google Drive as a synchronous call:

Tip: You can also enqueue read requests while not connected to Google Play services. For example, execute a method to read a file from Google Drive regardless of whether your Google API Client is connected yet. Then once a connection is established, the read requests execute and you’ll receive the results. Any write requests, however, will generate an error if you call them while your Google API Client is not connected.

Источник

Setup Instructions

If you are not using a generated library, you can download the Google API Client Library for Java and its dependencies in a zip file, or you can use Maven.

Читайте также:  Как извлечь удаленные файлы андроид

Also see the ProGuard setup instructions that are part of the Google HTTP Client Library for Java documentation.

Download the library with dependencies

Download the latest zip file, which you can find on the downloads page, and extract it on your computer. This zip file contains the client library class jar files and the associated source jar files for each artifact and its dependencies. You can find dependency graphs and licenses for the different libraries in the dependencies folder. For more details about the contents of the download, see the readme.html file.

Android

If you are developing for Android, and the Google API you want to use is included in the Google Play Services library, use the Google Play Services library for the best performance and experience.

If you are using the Google API Client Library for Java with Android, it is important to know which dependencies are compatible with Android, specifically which Android SDK level. Android applications require the following jar files, or newer compatible versions, from the libs folder:

Google App Engine

Google App Engine applications require the following jar files, or newer compatible versions, from the libs folder:

  • google-api-client-1.32.1.jar
  • google-api-client-appengine-1.32.1.jar
  • google-api-client-servlet-1.32.1.jar
  • google-oauth-client-1.31.5.jar
  • google-oauth-client-appengine-1.31.5.jar
  • google-oauth-client-servlet-1.31.5.jar
  • google-http-client-1.39.2.jar
  • google-http-client-appengine-1.39.2.jar
  • gson-2.8.7.jar
  • jackson-core-2.12.4.jar
  • jdo2-api-2.3-eb.jar
  • jsr305-3.0.2.jar
  • protobuf-java-3.17.2.jar
  • transaction-api-1.1.jar
  • xpp3-1.1.4c.jar

Servlet

Servlet applications require the following jar files, or newer compatible versions, from the libs folder:

  • google-api-client-1.32.1.jar
  • google-api-client-servlet-1.32.1.jar
  • google-oauth-client-1.31.5.jar
  • google-oauth-client-servlet-1.31.5.jar
  • google-http-client-1.39.2.jar
  • commons-logging-1.2.jar
  • gson-2.8.7.jar
  • httpclient-4.5.13.jar
  • httpcore-4.4.12.jar
  • jackson-core-2.12.4.jar
  • jdo2-api-2.3-eb.jar
  • jsr305-3.0.2.jar
  • protobuf-java-3.17.2.jar
  • transaction-api-1.1.jar
  • xpp3-1.1.4c.jar

Generic Java

General purpose Java applications require the following jar files, or newer compatible versions, from the libs folder:

  • google-api-client-1.32.1.jar
  • google-oauth-client-1.31.5.jar
  • google-http-client-1.39.2.jar
  • google-http-client-jackson2-1.39.2.jar
  • commons-logging-1.2.jar
  • gson-2.8.7.jar
  • httpclient-4.5.13.jar
  • httpcore-4.4.12.jar
  • jackson-core-2.12.4.jar
  • jsr305-3.0.2.jar
  • protobuf-java-3.17.2.jar
  • xpp3-1.1.4c.jar

Generated libraries for Google APIs

Maven

The Google API Client Library for Java is in the central Maven repository. The Maven groupId for all artifacts for this library is com.google.api-client . Specific Maven instructions are given for each module (below).

Modules

This library is composed of nine modules:

google-api-client

The Google API Client Library for Java (google-api-client) is designed to be compatible with all supported Java platforms, including Android.

On Android, you will need to explicitly exclude unused dependencies:

google-api-client-android

Extensions to the Google API Client Library for Java (google-api-client-android) support Java Google Android (only for SDK >= 2.1) applications. This module depends on google-api-client and google-http-client-android.

google-api-client-servlet

Servlet and JDO extensions to the Google API Client Library for Java (google-api-client-servlet) support Java servlet web applications. This module depends on google-api-client and google-oauth-client-servlet.

google-api-client-appengine

Google App Engine extensions to the Google API Client Library for Java (google-api-client-appengine) support Java Google App Engine applications. This module depends on google-api-client, google-api-client-servlet, google-oauth-client-appengine and google-http-client-appengine.

google-api-client-gson

GSON extensions to the Google API Client Library for Java (google-api-client-gson). This module depends on google-api-client and google-http-client-gson.

google-api-client-jackson2

Jackson2 extensions to the Google API Client Library for Java (google-api-client-jackson2). This module depends on google-api-client and google-http-client-jackson2.

google-api-client-java6

Java 6 (and higher) extensions to the Google API Client Library for Java (google-api-client-java6). This module depends on google-api-client and google-oauth-client-java6.

google-api-client-protobuf

Protocol buffer extensions to the Google API Client Library for Java (google-api-client-protobuf). This module depends on google-http-client-protobuf and google-api-client.

google-api-client-xml

XML extensions to the Google API Client Library for Java (google-api-client-xml). This module depends on google-api-client and google-http-client-xml.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Оцените статью