Scott Main | a4c5bba | 2013-10-04 19:08:08 -0700 | [diff] [blame] | 1 | page.title=Accessing Google Play Services APIs |
| 2 | page.tags="oauth 2.0","GoogleAuthUtil" |
| 3 | |
| 4 | trainingnavtop=true |
| 5 | startpage=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 |
| 32 | library (such as Google+, Games, or Drive), you need to create an instance of <a |
| 33 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 34 | GoogleApiClient}</a> ("Google API Client"). The Google API Client provides a common entry point to all |
| 35 | the Google Play services and manages the network connection between the user's device and each |
| 36 | Google 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 |
| 41 | connect using the appropriate REST API, but you must obtain an OAuth 2.0 token. For more |
| 42 | information, read <a href="{@docRoot}google/auth/http-auth.html">Authorizing with Google |
| 43 | for 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 |
| 54 | subclass of <a |
| 55 | href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.html">{@code GooglePlayServicesClient}</a>, you should migrate to <a |
| 56 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 57 | GoogleApiClient}</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 |
| 63 | interface for connecting and making calls to any of the available Google Play services such as |
| 64 | Google 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 |
| 69 | your Android SDK. If you haven't done so already, follow the instructions in <a |
| 70 | href="{@docRoot}google/play-services/setup.html">Set Up Google |
| 71 | Play 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 |
| 79 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 80 | GoogleApiClient}</a> using the <a |
| 81 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html">{@code |
| 82 | GoogleApiClient.Builder}</a> APIs in your activity's {@link |
| 83 | android.app.Activity#onCreate onCreate()} method. The <a |
| 84 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html">{@code |
| 85 | GoogleApiClient.Builder}</a> class |
| 86 | provides methods that allow you to specify the Google APIs you want to use and your desired OAuth |
| 87 | 2.0 scopes. For example, here's a <a |
| 88 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 89 | GoogleApiClient}</a> instance that connects with the Google |
| 90 | Drive service:</p> |
| 91 | <pre> |
| 92 | GoogleApiClient 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 |
| 99 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 100 | GoogleApiClient}</a> by appending |
| 101 | additional 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 |
| 108 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()" |
| 109 | >{@code connect()}</a> on the <a |
| 110 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 111 | GoogleApiClient}</a>, you must specify an implementation for the callback interfaces, <a |
| 112 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html" |
| 113 | >{@code ConnectionCallbacks}</a> and <a |
| 114 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.OnConnectionFailedListener.html" |
Scott Main | 64b6f26 | 2014-02-12 12:16:11 -0800 | [diff] [blame] | 115 | >{@code OnConnectionFailedListener}</a>. These interfaces receive callbacks in |
Scott Main | a4c5bba | 2013-10-04 19:08:08 -0700 | [diff] [blame] | 116 | response to the asynchronous <a |
| 117 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()" |
| 118 | >{@code connect()}</a> method when the connection to Google Play services |
| 119 | succeeds, 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 |
| 122 | API Client:</p> |
| 123 | |
| 124 | <pre> |
| 125 | import gms.common.api.*; |
| 126 | import gms.drive.*; |
| 127 | import android.support.v4.app.FragmentActivity; |
| 128 | |
| 129 | public class MyActivity extends FragmentActivity |
| 130 | implements ConnectionCallbacks, OnConnectionFailedListener { |
| 131 | private GoogleApiClient mGoogleApiClient; |
| 132 | |
| 133 | @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 | @Override |
| 148 | public void onConnected(Bundle connectionHint) { |
| 149 | // Connected to Google Play services! |
| 150 | // The good stuff goes here. |
| 151 | } |
| 152 | |
| 153 | @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 | @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 |
| 172 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()" |
| 173 | >{@code connect()}</a>. To gracefully manage |
| 174 | the lifecycle of the connection, you should call <a |
| 175 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()" |
| 176 | >{@code connect()}</a> during the activity's {@link |
| 177 | android.app.Activity#onStart onStart()} (unless you want to connect later), then call <a |
| 178 | href="{@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 | @Override |
| 182 | protected void onStart() { |
| 183 | super.onStart(); |
| 184 | if (!mResolvingError) { // more about this later |
| 185 | mGoogleApiClient.connect(); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | @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 |
| 197 | to <a |
| 198 | href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesClient.OnConnectionFailedListener.html#onConnectionFailed(com.google.android.gms.common.ConnectionResult)" |
| 199 | >{@code onConnectionFailed()}</a> with the <a |
| 200 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#SIGN_IN_REQUIRED" |
| 201 | >{@code SIGN_IN_REQUIRED}</a> error because the user account |
| 202 | has 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 |
| 210 | href="{@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 |
| 212 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#hasResolution()" |
| 213 | >{@code hasResolution()}</a> on the provided <a |
| 214 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html" |
| 215 | >{@code ConnectionResult}</a> object. If it returns true, you can |
| 216 | request the user take immediate action to resolve the error by calling <a |
| 217 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)">{@code startResolutionForResult()}</a> on the <a |
| 218 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html" |
| 219 | >{@code ConnectionResult}</a> object. The <a |
| 220 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)" |
| 221 | >{@code startResolutionForResult()}</a> behaves the same as {@link |
| 222 | android.app.Activity#startActivityForResult startActivityForResult()} and launches the |
| 223 | appropriate activity for the user |
| 224 | to resolve the error (such as an activity to select an account).</p> |
| 225 | |
| 226 | <p>If <a |
| 227 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#hasResolution()" |
| 228 | >{@code hasResolution()}</a> returns false, you should instead call <a |
| 229 | href="{@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 |
| 231 | android.app.Dialog} provided by Google Play services that's appropriate for the given error. The |
| 232 | dialog may simply provide a message explaining the error, but it may also provide an action to |
| 233 | launch an activity that can resolve the error (such as when the user needs to install a newer |
| 234 | version of Google Play services).</p> |
| 235 | |
| 236 | <p>For example, your <a |
| 237 | href="{@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> |
| 241 | public 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 | @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 | @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 | @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 |
| 312 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)" |
| 313 | >{@code startResolutionForResult()}</a> or <a |
| 314 | href="{@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 |
| 316 | android.app.Activity#onActivityResult onActivityResult()} callback with the {@link |
| 317 | android.app.Activity#RESULT_OK} |
| 318 | result code. You can then call <a |
| 319 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()" |
| 320 | >{@code connect()}</a> again. For example:</p> |
| 321 | |
| 322 | <pre> |
| 323 | @Override |
| 324 | protected 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 |
| 339 | the app state while the user is resolving the error to avoid repetitive attempts to resolve the |
| 340 | same error. For instance, while the account picker dialog is showing to resolve the <a |
| 341 | href="{@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 |
| 343 | your {@link android.app.Activity#onStart onStart()} method to be called again, which then calls <a |
| 344 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html#connect()" |
| 345 | >{@code connect()}</a> again. This results in another call to <a |
| 346 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)" |
| 347 | >{@code startResolutionForResult()}</a>, which |
| 348 | creates another account picker dialog in front of the existing one.</p> |
| 349 | |
| 350 | <p>This boolean is effective only |
| 351 | if 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 |
| 358 | href="{@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 |
| 360 | error is ongoing, you need to retain a boolean that tracks whether your app is already attempting |
| 361 | to 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 |
| 364 | href="{@docRoot}reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)" |
| 365 | >{@code startResolutionForResult()}</a> or display the dialog from <a |
| 366 | href="{@docRoot}reference/com/google/android/gms/common/GooglePlayServicesUtil.html#getErrorDialog(int, android.app.Activity, int)" |
| 367 | >{@code GooglePlayServicesUtil.getErrorDialog()}</a>. Then when you |
| 368 | receive {@link android.app.Activity#RESULT_OK} in the {@link android.app.Activity#onActivityResult |
| 369 | onActivityResult()} 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), |
| 372 | save the boolean in the activity's saved instance data using {@link |
| 373 | android.app.Activity#onSaveInstanceState onSaveInstanceState()}:</p> |
| 374 | |
| 375 | <pre> |
| 376 | private static final String STATE_RESOLVING_ERROR = "resolving_error"; |
| 377 | |
| 378 | @Override |
| 379 | protected 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 | @Override |
| 389 | protected 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. |
| 399 | How you can perform read and write requests to any of the Google Play services |
| 400 | using <a |
| 401 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 402 | GoogleApiClient}</a> is discussed in the next section.</p> |
| 403 | |
| 404 | <p>For more information about each services's APIs available once you're connected, |
| 405 | consult 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 |
| 416 | your app is authorized, as specified by the APIs and scopes you added to your <a |
| 417 | href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code |
| 418 | GoogleApiClient}</a> instance.</p> |
| 419 | |
| 420 | <p class="note"> |
| 421 | <strong>Note:</strong> Before making calls to specific Google services, you may first need to |
| 422 | register your app in the Google Developer Console. For specific instructions, refer to the |
| 423 | appropriate 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 |
| 428 | as a <a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">{@code |
| 429 | PendingResult}</a> object. This is an object representing the request, which hasn't yet |
| 430 | been 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 |
| 434 | PendingResult}</a> object:</p> |
| 435 | |
| 436 | <pre> |
| 437 | Query query = new Query.Builder() |
| 438 | .addFilter(Filters.eq(SearchableField.TITLE, filename)); |
| 439 | PendingResult 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 |
| 444 | PendingResult}</a>, you can continue by making the request either asynchronous |
| 445 | or synchronous.</p> |
| 446 | |
| 447 | |
| 448 | <h3 id="Async">Using asynchronous calls</h3> |
| 449 | |
| 450 | <p>To make the request asynchronous, call <a |
| 451 | href="{@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 |
| 454 | PendingResult}</a> and |
| 455 | provide an implementation of the <a |
| 456 | href="{@docRoot}reference/com/google/android/gms/common/api/ResultCallback.html" |
| 457 | >{@code ResultCallback}</a> interface. For example, here's the request |
| 458 | executed asynchronously:</p> |
| 459 | |
| 460 | <pre> |
| 461 | private 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<DriveApi.MetadataBufferResult>() { |
| 469 | @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 |
| 479 | href="{@docRoot}reference/com/google/android/gms/common/api/Result.html">{@code Result}</a> |
| 480 | object in the <a |
| 481 | href="{@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 |
| 483 | appropriate subclass as specified by the API you're using, such as <a |
| 484 | href="{@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 |
| 491 | call is needed as an argument to another, you can make your request synchronous by calling <a |
| 492 | href="{@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 |
| 495 | PendingResult}</a>. This blocks the thread and returns the <a |
| 496 | href="{@docRoot}reference/com/google/android/gms/common/api/Result.html">{@code Result}</a> object |
| 497 | when the request completes, which is delivered as an instance of the |
| 498 | appropriate subclass as specified by the API you're using, such as <a |
| 499 | href="{@docRoot}reference/com/google/android/gms/drive/DriveApi.MetadataBufferResult.html" |
| 500 | >{@code DriveApi.MetadataBufferResult}</a>.</p> |
| 501 | |
| 502 | <p>Because calling <a |
| 503 | href="{@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 |
| 505 | never perform this call on the UI thread. So, if you want to perform synchronous requests to a |
| 506 | Google Play service, you should create a new thread, such as with {@link android.os.AsyncTask} in |
| 507 | which to perform the request. For example, here's how to perform the same file request to Google |
| 508 | Drive as a synchronous call:</p> |
| 509 | |
| 510 | <pre> |
| 511 | private void loadFile(String filename) { |
| 512 | new GetFileTask().execute(filename); |
| 513 | } |
| 514 | |
Scott Main | 64b6f26 | 2014-02-12 12:16:11 -0800 | [diff] [blame] | 515 | private class GetFileTask extends AsyncTask<String, Void, Void> { |
Scott Main | a4c5bba | 2013-10-04 19:08:08 -0700 | [diff] [blame] | 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 |
| 532 | services. For example, execute a method to read a file from Google Drive regardless of whether your |
| 533 | Google API Client is connected yet. Then once a connection is established, the read requests |
| 534 | execute and you'll receive the results. Any write requests, however, will generate an error if you |
| 535 | call them while your Google API Client is not connected.</p> |
| 536 | |