• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Accessing Google APIs
2page.tags="oauth 2.0","GoogleAuthUtil"
3
4trainingnavtop=true
5startpage=true
6
7@jd:body
8
9<div id="qv-wrapper">
10  <div id="qv">
11
12<h2>In this document</h2>
13<ol>
14  <li><a href="#Starting">Start a Connection</a>
15    <ol>
16      <li><a href="#HandlingFailures">Handle connection failures</a></li>
17      <li><a href="#MaintainingState">Maintain state while resolving an error</a></li>
18    </ol>
19  </li>
20  <li><a href="#Communicating">Communicate with Google Services</a>
21    <ol>
22      <li><a href="#Async">Using asynchronous calls</a></li>
23      <li><a href="#Sync">Using synchronous calls</a></li>
24    </ol>
25  </li>
26</ol>
27</div>
28</div>
29
30
31<p>When you want to make a connection to one of the Google APIs provided in the Google Play services
32library (such as Google+, Games, or Drive), you need to create an instance of <a
33href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
34GoogleApiClient}</a> ("Google API Client"). The Google API Client provides a common entry point to all
35the Google Play services and manages the network connection between the user's device and each
36Google service.</p>
37
38<div class="sidebox" style="clear:right;width:190px">
39<h2>Connecting to REST APIs</h2>
40<p>If the Google API you want to use is not included in the Google Play services library, you can
41connect using the appropriate REST API, but you must obtain an OAuth 2.0 token. For more
42information, read <a href="{@docRoot}google/auth/http-auth.html">Authorizing with Google
43for REST APIs</a>.</p>
44</div>
45
46<p>This guide shows how you can use Google API Client to:</p>
47<ul>
48<li>Connect to one or more Google Play services asynchronously and handle failures.</li>
49<li>Perform synchronous and asynchronous API calls to any of the Google Play services.</li>
50</ul>
51
52<p class="note">
53<strong>Note:</strong> If you have an existing app that connects to Google Play services with a
54subclass of <a
55href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.html">{@code GooglePlayServicesClient}</a>, you should migrate to <a
56href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
57GoogleApiClient}</a> as soon as possible.</p>
58
59
60<img src="{@docRoot}images/google/GoogleApiClient@2x.png" width="464px" alt="" />
61<p class="img-caption">
62<strong>Figure 1.</strong> An illustration showing how the Google API Client provides an
63interface for connecting and making calls to any of the available Google Play services such as
64Google Play Games and Google Drive.</p>
65
66
67
68<p>To get started, you must first install the Google Play services library (revision 15 or higher) for
69your Android SDK. If you haven't done so already, follow the instructions in <a
70href="{@docRoot}google/play-services/setup.html">Set Up Google
71Play Services SDK</a>.</p>
72
73
74
75
76<h2 id="Starting">Start a Connection</h2>
77
78<p>Once your project is linked to the Google Play services library, create an instance of <a
79href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
80GoogleApiClient}</a> using the <a
81href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html">{@code
82GoogleApiClient.Builder}</a> APIs in your activity's {@link
83android.app.Activity#onCreate onCreate()} method. The <a
84href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html">{@code
85GoogleApiClient.Builder}</a> class
86provides methods that allow you to specify the Google APIs you want to use and your desired OAuth
872.0 scopes. For example, here's a <a
88href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
89GoogleApiClient}</a> instance that connects with the Google
90Drive service:</p>
91<pre>
92GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
93    .addApi(Drive.API)
94    .addScope(Drive.SCOPE_FILE)
95    .build();
96</pre>
97
98<p>You can add multiple APIs and multiple scopes to the same <a
99href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
100GoogleApiClient}</a> by appending
101additional calls to
102<a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#addApi(com.google.android.gms.common.api.Api)"
103>{@code addApi()}</a> and
104<a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#addScope(com.google.android.gms.common.api.Scope)"
105>{@code addScope()}</a>.</p>
106
107<p>However, before you can begin a connection by calling <a
108href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()"
109>{@code connect()}</a> on the <a
110href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
111GoogleApiClient}</a>, you must specify an implementation for the callback interfaces, <a
112href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html"
113>{@code ConnectionCallbacks}</a> and <a
114href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.OnConnectionFailedListener.html"
115>{@code OnConnectionFailedListener}</a>. These interfaces receive callbacks in
116response to the asynchronous <a
117href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()"
118>{@code connect()}</a> method when the connection to Google Play services
119succeeds, fails, or becomes suspended.</p>
120
121<p>For example, here's an activity that implements the callback interfaces and adds them to the Google
122API Client:</p>
123
124<pre>
125import gms.common.api.*;
126import gms.drive.*;
127import android.support.v4.app.FragmentActivity;
128
129public class MyActivity extends FragmentActivity
130        implements ConnectionCallbacks, OnConnectionFailedListener {
131    private GoogleApiClient mGoogleApiClient;
132
133    &#64;Override
134    protected void onCreate(Bundle savedInstanceState) {
135        super.onCreate(savedInstanceState);
136
137        // Create a GoogleApiClient instance
138        mGoogleApiClient = new GoogleApiClient.Builder(this)
139                .addApi(Drive.API)
140                .addScope(Drive.SCOPE_FILE)
141                .addConnectionCallbacks(this)
142                .addOnConnectionFailedListener(this)
143                .build();
144        ...
145    }
146
147    &#64;Override
148    public void onConnected(Bundle connectionHint) {
149        // Connected to Google Play services!
150        // The good stuff goes here.
151    }
152
153    &#64;Override
154    public void onConnectionSuspended(int cause) {
155        // The connection has been interrupted.
156        // Disable any UI components that depend on Google APIs
157        // until onConnected() is called.
158    }
159
160    &#64;Override
161    public void onConnectionFailed(ConnectionResult result) {
162        // This callback is important for handling errors that
163        // may occur while attempting to connect with Google.
164        //
165        // More about this in the next section.
166        ...
167    }
168}
169</pre>
170
171<p>With the callback interfaces defined, you're ready to call <a
172href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()"
173>{@code connect()}</a>. To gracefully manage
174the lifecycle of the connection, you should call <a
175href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()"
176>{@code connect()}</a> during the activity's {@link
177android.app.Activity#onStart onStart()} (unless you want to connect later), then call <a
178href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#disconnect()"
179>{@code disconnect()}</a> during the {@link android.app.Activity#onStop onStop()} method. For example:</p>
180<pre>
181    &#64;Override
182    protected void onStart() {
183        super.onStart();
184        if (!mResolvingError) {  // more about this later
185            mGoogleApiClient.connect();
186        }
187    }
188
189    &#64;Override
190    protected void onStop() {
191        mGoogleApiClient.disconnect();
192        super.onStop();
193    }
194</pre>
195
196<p>However, if you run this code, there's a good chance it will fail and your app will receive a call
197to <a
198href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.OnConnectionFailedListener.html#onConnectionFailed(com.google.android.gms.common.ConnectionResult)"
199>{@code onConnectionFailed()}</a> with the <a
200href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#SIGN_IN_REQUIRED"
201>{@code SIGN_IN_REQUIRED}</a> error because the user account
202has not been specified. The next section shows how to handle this error and others.</p>
203
204
205
206
207<h3 id="HandlingFailures">Handle connection failures</h3>
208
209<p>When you receive a call to the <a
210href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.OnConnectionFailedListener.html#onConnectionFailed(com.google.android.gms.common.ConnectionResult)"
211>{@code onConnectionFailed()}</a> callback, you should call <a
212href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#hasResolution()"
213>{@code hasResolution()}</a> on the provided <a
214href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html"
215>{@code ConnectionResult}</a> object. If it returns true, you can
216request the user take immediate action to resolve the error by calling <a
217href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)">{@code startResolutionForResult()}</a> on the <a
218href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html"
219>{@code ConnectionResult}</a> object. The <a
220href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)"
221>{@code startResolutionForResult()}</a> behaves the same as {@link
222android.app.Activity#startActivityForResult startActivityForResult()} and launches the
223appropriate activity for the user
224to resolve the error (such as an activity to select an account).</p>
225
226<p>If <a
227href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#hasResolution()"
228>{@code hasResolution()}</a> returns false, you should instead call <a
229href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesUtil.html#getErrorDialog(int, android.app.Activity, int)"
230>{@code GooglePlayServicesUtil.getErrorDialog()}</a>, passing it the error code. This returns a {@link
231android.app.Dialog} provided by Google Play services that's appropriate for the given error. The
232dialog may simply provide a message explaining the error, but it may also provide an action to
233launch an activity that can resolve the error (such as when the user needs to install a newer
234version of Google Play services).</p>
235
236<p>For example, your <a
237href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.OnConnectionFailedListener.html#onConnectionFailed(com.google.android.gms.common.ConnectionResult)"
238>{@code onConnectionFailed()}</a> callback method should now look like this:</p>
239
240<pre>
241public class MyActivity extends FragmentActivity
242        implements ConnectionCallbacks, OnConnectionFailedListener {
243
244    // Request code to use when launching the resolution activity
245    private static final int REQUEST_RESOLVE_ERROR = 1001;
246    // Unique tag for the error dialog fragment
247    private static final String DIALOG_ERROR = "dialog_error";
248    // Bool to track whether the app is already resolving an error
249    private boolean mResolvingError = false;
250
251    ...
252
253    &#64;Override
254    public void onConnectionFailed(ConnectionResult result) {
255        if (mResolvingError) {
256            // Already attempting to resolve an error.
257            return;
258        } else if (result.hasResolution()) {
259            try {
260                mResolvingError = true;
261                result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
262            } catch (SendIntentException e) {
263                // There was an error with the resolution intent. Try again.
264                mGoogleApiClient.connect();
265            }
266        } else {
267            // Show dialog using GooglePlayServicesUtil.getErrorDialog()
268            showErrorDialog(result.getErrorCode());
269            mResolvingError = true;
270        }
271    }
272
273    // The rest of this code is all about building the error dialog
274
275    /* Creates a dialog for an error message */
276    private void showErrorDialog(int errorCode) {
277        // Create a fragment for the error dialog
278        ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
279        // Pass the error that should be displayed
280        Bundle args = new Bundle();
281        args.putInt(DIALOG_ERROR, errorCode);
282        dialogFragment.setArguments(args);
283        dialogFragment.show(getSupportFragmentManager(), "errordialog");
284    }
285
286    /* Called from ErrorDialogFragment when the dialog is dismissed. */
287    public void onDialogDismissed() {
288        mResolvingError = false;
289    }
290
291    /* A fragment to display an error dialog */
292    public static class ErrorDialogFragment extends DialogFragment {
293        public ErrorDialogFragment() { }
294
295        &#64;Override
296        public Dialog onCreateDialog(Bundle savedInstanceState) {
297            // Get the error code and retrieve the appropriate dialog
298            int errorCode = this.getArguments().getInt(DIALOG_ERROR);
299            return GooglePlayServicesUtil.getErrorDialog(errorCode,
300                    this.getActivity(), REQUEST_RESOLVE_ERROR);
301        }
302
303        &#64;Override
304        public void onDismiss(DialogInterface dialog) {
305            ((MainActivity)getActivity()).onDialogDismissed();
306        }
307    }
308}
309</pre>
310
311<p>Once the user completes the resolution provided by <a
312href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)"
313>{@code startResolutionForResult()}</a> or <a
314href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesUtil.html#getErrorDialog(int, android.app.Activity, int)"
315>{@code GooglePlayServicesUtil.getErrorDialog()}</a>, your activity receives the {@link
316android.app.Activity#onActivityResult onActivityResult()} callback with the {@link
317android.app.Activity#RESULT_OK}
318result code. You can then call <a
319href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()"
320>{@code connect()}</a> again. For example:</p>
321
322<pre>
323&#64;Override
324protected void onActivityResult(int requestCode, int resultCode, Intent data) {
325    if (requestCode == REQUEST_RESOLVE_ERROR) {
326        mResolvingError = false;
327        if (resultCode == RESULT_OK) {
328            // Make sure the app is not already connected or attempting to connect
329            if (!mGoogleApiClient.isConnecting() &&
330                    !mGoogleApiClient.isConnected()) {
331                mGoogleApiClient.connect();
332            }
333        }
334    }
335}
336</pre>
337
338<p>In the above code, you probably noticed the boolean, {@code mResolvingError}. This keeps track of
339the app state while the user is resolving the error to avoid repetitive attempts to resolve the
340same error. For instance, while the account picker dialog is showing to resolve the <a
341href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#SIGN_IN_REQUIRED"
342>{@code SIGN_IN_REQUIRED}</a> error, the user may rotate the screen. This recreates your activity and causes
343your {@link android.app.Activity#onStart onStart()} method to be called again, which then calls <a
344href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()"
345>{@code connect()}</a> again. This results in another call to <a
346href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)"
347>{@code startResolutionForResult()}</a>, which
348creates another account picker dialog in front of the existing one.</p>
349
350<p>This boolean is effective only
351if retained across activity instances, though. The next section explains further.</p>
352
353
354
355<h3 id="MaintainingState">Maintain state while resolving an error</h3>
356
357<p>To avoid executing the code in <a
358href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.OnConnectionFailedListener.html#onConnectionFailed(com.google.android.gms.common.ConnectionResult)"
359>{@code onConnectionFailed()}</a> while a previous attempt to resolve an
360error is ongoing, you need to retain a boolean that tracks whether your app is already attempting
361to resolve an error.</p>
362
363<p>As shown in the code above, you should set a boolean to {@code true} each time you call <a
364href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)"
365>{@code startResolutionForResult()}</a> or display the dialog from <a
366href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesUtil.html#getErrorDialog(int, android.app.Activity, int)"
367>{@code GooglePlayServicesUtil.getErrorDialog()}</a>. Then when you
368receive {@link android.app.Activity#RESULT_OK} in the {@link android.app.Activity#onActivityResult
369onActivityResult()} callback, set the boolean to {@code false}.</p>
370
371<p>To keep track of the boolean across activity restarts (such as when the user rotates the screen),
372save the boolean in the activity's saved instance data using {@link
373android.app.Activity#onSaveInstanceState onSaveInstanceState()}:</p>
374
375<pre>
376private static final String STATE_RESOLVING_ERROR = "resolving_error";
377
378&#64;Override
379protected void onSaveInstanceState(Bundle outState) {
380    super.onSaveInstanceState(outState);
381    outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
382}
383</pre>
384
385<p>Then recover the saved state during {@link android.app.Activity#onCreate onCreate()}:</p>
386
387<pre>
388&#64;Override
389protected void onCreate(Bundle savedInstanceState) {
390    super.onCreate(savedInstanceState);
391
392    ...
393    mResolvingError = savedInstanceState != null
394            && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
395}
396</pre>
397
398<p>Now you're ready to safely run your app and connect to Google Play services.
399How you can perform read and write requests to any of the Google Play services
400using <a
401href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
402GoogleApiClient}</a> is discussed in the next section.</p>
403
404<p>For more information about each services's APIs available once you're connected,
405consult the corresponding documentation, such as for
406<a href="{@docRoot}google/play-services/games.html">Google Play Games</a> or
407<a href="{@docRoot}google/play-services/drive.html">Google Drive</a>.
408</p>
409
410
411
412
413<h2 id="Communicating">Communicate with Google Services</h2>
414
415<p>Once connected, your client can make read and write calls using the service-specific APIs for which
416your app is authorized, as specified by the APIs and scopes you added to your <a
417href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code
418GoogleApiClient}</a> instance.</p>
419
420<p class="note">
421<strong>Note:</strong> Before making calls to specific Google services, you may first need to
422register your app in the Google Developer Console. For specific instructions, refer to the
423appropriate getting started guide for the API you're using, such as <a href=
424"https://developers.google.com/drive/android/get-started">Google Drive</a> or <a href=
425"https://developers.google.com/+/mobile/android/getting-started">Google+</a>.</p>
426
427<p>When you perform a read or write request using Google API Client, the immediate result is returned
428as a <a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">{@code
429PendingResult}</a> object. This is an object representing the request, which hasn't yet
430been delivered to the Google service.</p>
431
432<p>For example, here's a request to read a file from Google Drive that provides a
433<a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">{@code
434PendingResult}</a> object:</p>
435
436<pre>
437Query query = new Query.Builder()
438        .addFilter(Filters.eq(SearchableField.TITLE, filename));
439PendingResult result = Drive.DriveApi.query(mGoogleApiClient, query);
440</pre>
441
442<p>Once you have the
443<a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">{@code
444PendingResult}</a>, you can continue by making the request either asynchronous
445or synchronous.</p>
446
447
448<h3 id="Async">Using asynchronous calls</h3>
449
450<p>To make the request asynchronous, call <a
451href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html#setResultCallback(com.google.android.gms.common.api.ResultCallback<R>)"
452>{@code setResultCallback()}</a> on the
453<a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">{@code
454PendingResult}</a> and
455provide an implementation of the <a
456href="{@docRoot}reference/com/google/android/gms/common/api/ResultCallback.html"
457>{@code ResultCallback}</a> interface. For example, here's the request
458executed asynchronously:</p>
459
460<pre>
461private void loadFile(String filename) {
462    // Create a query for a specific filename in Drive.
463    Query query = new Query.Builder()
464            .addFilter(Filters.eq(SearchableField.TITLE, filename))
465            .build();
466    // Invoke the query asynchronously with a callback method
467    Drive.DriveApi.query(mGoogleApiClient, query)
468            .setResultCallback(new ResultCallback&lt;DriveApi.MetadataBufferResult>() {
469        &#64;Override
470        public void onResult(DriveApi.MetadataBufferResult result) {
471            // Success! Handle the query result.
472            ...
473        }
474    });
475}
476</pre>
477
478<p>When your app receives a <a
479href="{@docRoot}reference/com/google/android/gms/common/api/Result.html">{@code Result}</a>
480object in the <a
481href="{@docRoot}reference/com/google/android/gms/common/api/ResultCallback.html#onResult(R)"
482>{@code onResult()}</a> callback, it is delivered as an instance of the
483appropriate subclass as specified by the API you're using, such as <a
484href="{@docRoot}reference/com/google/android/gms/drive/DriveApi.MetadataBufferResult.html"
485>{@code DriveApi.MetadataBufferResult}</a>.</p>
486
487
488<h3 id="Sync">Using synchronous calls</h3>
489
490<p>If you want your code to execute in a strictly defined order, perhaps because the result of one
491call is needed as an argument to another, you can make your request synchronous by calling <a
492href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html#await()"
493>{@code await()}</a> on the
494<a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">{@code
495PendingResult}</a>. This blocks the thread and returns the <a
496href="{@docRoot}reference/com/google/android/gms/common/api/Result.html">{@code Result}</a> object
497when the request completes, which is delivered as an instance of the
498appropriate subclass as specified by the API you're using, such as <a
499href="{@docRoot}reference/com/google/android/gms/drive/DriveApi.MetadataBufferResult.html"
500>{@code DriveApi.MetadataBufferResult}</a>.</p>
501
502<p>Because calling <a
503href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html#await()"
504>{@code await()}</a> blocks the thread until the result arrives, it's important that you
505never perform this call on the UI thread. So, if you want to perform synchronous requests to a
506Google Play service, you should create a new thread, such as with {@link android.os.AsyncTask} in
507which to perform the request. For example, here's how to perform the same file request to Google
508Drive as a synchronous call:</p>
509
510<pre>
511private void loadFile(String filename) {
512    new GetFileTask().execute(filename);
513}
514
515private class GetFileTask extends AsyncTask&lt;String, Void, Void> {
516    protected void doInBackground(String filename) {
517        Query query = new Query.Builder()
518                .addFilter(Filters.eq(SearchableField.TITLE, filename))
519                .build();
520        // Invoke the query synchronously
521        DriveApi.MetadataBufferResult result =
522                Drive.DriveApi.query(mGoogleApiClient, query).await();
523
524        // Continue doing other stuff synchronously
525        ...
526    }
527}
528</pre>
529
530<p class="note">
531<strong>Tip:</strong> You can also enqueue read requests while not connected to Google Play
532services. For example, execute a method to read a file from Google Drive regardless of whether your
533Google API Client is connected yet. Then once a connection is established, the read requests
534execute and you'll receive the results. Any write requests, however, will generate an error if you
535call them while your Google API Client is not connected.</p>
536
537