public final class

GoogleAuthUtil

extends Object
java.lang.Object
   ↳ com.google.android.gms.auth.GoogleAuthUtil

Class Overview

GoogleAuthUtil provides static utility methods to acquire and invalidate authentication tokens.

   public void onCreate {
       // onCreate is called on the main thread, so you must do the work in
       // a background thread, which AsyncTask makes easy to do.
       getAndUseAuthTokenInAsyncTask();
   }

   ...

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == MY_ACTIVITYS_AUTH_REQUEST_CODE) {
           if (resultCode == RESULT_OK) {
               getAndUseAuthTokenInAsyncTask();
           }
       }
   }

   // Example of how to use the GoogleAuthUtil in a blocking, non-main thread context
   void getAndUseAuthTokenBlocking() {
       try {
          // Retrieve a token for the given account and scope. It will always return either
          // a non-empty String or throw an exception.
          final String token = GoogleAuthUtil.getToken(Context, String, String)(context, email, scope);
          // Do work with token.
          ...
          if (server indicates token is invalid) {
              // invalidate the token that we found is bad so that GoogleAuthUtil won't
              // return it next time (it may have cached it)
              GoogleAuthUtil.invalidateToken(Context, String)(context, token);
              // consider retrying getAndUseTokenBlocking() once more
              return;
          }
          return;
       } catch (GooglePlayServicesAvailabilityException playEx) {
         Dialog alert = GooglePlayServicesUtil.getErrorDialog(
             playEx.getConnectionStatusCode(),
             this,
             MY_ACTIVITYS_AUTH_REQUEST_CODE);
         ...
       } catch (UserRecoverableAuthException userAuthEx) {
          // Start the user recoverable action using the intent returned by
          // getIntent()
          myActivity.startActivityForResult(
                  userAuthEx.getIntent(),
                  MY_ACTIVITYS_AUTH_REQUEST_CODE);
          return;
       } catch (IOException transientEx) {
          // network or server error, the call is expected to succeed if you try again later.
          // Don't attempt to call again immediately - the request is likely to
          // fail, you'll hit quotas or back-off.
          ...
          return;
       } catch (GoogleAuthException authEx) {
          // Failure. The call is not expected to ever succeed so it should not be
          // retried.
          ...
          return;
       }
   }

   // Example of how to use AsyncTask to call blocking code on a background thread.
   void getAndUseAuthTokenInAsyncTask() {
       AsyncTask task = new AsyncTask() {
           @Override
           protected Void doInBackground(Void... params) {
               getAndUseAuthTokenBlocking();
           }
       };
       task.execute((Void)null);
   }
 

Summary

Constants
String GOOGLE_ACCOUNT_TYPE
String KEY_HANDLE_NOTIFICATION
Public Methods
static String getToken(Context context, String accountName, String scope)
Authenticates the user and returns a valid Google authentication token, or throws an exception if there was an error getting a token.
static String getToken(Context context, String accountName, String scope, Bundle extras)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras, Intent callback)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras, String authority, Bundle syncBundle)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static void invalidateToken(Context context, String token)
Invalidates the specified token with respect to the Context.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final String GOOGLE_ACCOUNT_TYPE

Constant Value: "com.google"

public static final String KEY_HANDLE_NOTIFICATION

Constant Value: "handle_notification"

Public Methods

public static String getToken (Context context, String accountName, String scope)

Authenticates the user and returns a valid Google authentication token, or throws an exception if there was an error getting a token.

The exception thrown depends upon the underlying error and support for recovery. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered from programmatically. Some may be fatal errors stemming from implementation errors while others may require user intervention. UserRecoverableAuthExceptions are GoogleAuthExceptions that provide Intents which can be used to initiate any user intervention required to fix the underlying error. For example, a UserRecoverableAuthExceptions intent might lead to a request for a user's consent or present the user with a device policy manager download screen. GooglePlayServicesAvailabilityExceptions are UserRecoverableAuthExceptions along with a connection status code which allows clients to create a localized Dialog using getErrorDialog(int, android.app.Activity, int). Finally, this method is blocking and shouldn't be called in the main event thread. If so an IllegalStateException will be thrown.

Which exceptions should be handled and how depends on the context of the code. For example in the case of an Activity where the user is actively engaged:

 String token;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope);
 } catch (GooglePlayServicesAvailabilityException playEx) {
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
         playEx.getConnectionStatusCode(),
         Activity.this,
         AUTH_REQUEST_CODE);
     // Use the dialog to present to the user.
 } catch (UserRecoverableAutException recoverableException) {
     Intent recoveryIntent = recoverableException.getIntent();
     // Use the intent in a custom dialog or just startActivityForResult.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 
On the other hand, explicitly handling a GooglePlayServicesAvailabilityException in the absence of a UI thread may not be worthwhile. Instead a Notification may be preferable.
 String token;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope);
 } catch (UserRecoverableAuthException recoverableException) {
     Intent recoveryIntent = recoverableException.getIntent();
     // Use the intent to create a Notification.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMessage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope.
Returns
  • String containing a valid token.
Throws
GooglePlayServicesAvailabilityException containing the appropriate connection status error code.
UserRecoverableAuthException wrapping an Intent for initiating user intervention. The wrapped intent must be called with startActivityForResult(Intent, int).
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalArgumentException if the method is invoked in the main event thread.

public static String getToken (Context context, String accountName, String scope, Bundle extras)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

The exception thrown depends upon the underlying error and support for recovery. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered from programmatically. Some may be fatal errors stemming from implementation errors while others may require user intervention. UserRecoverableAuthExceptions are GoogleAuthExceptions that provide Intents which can be used to initiate any user intervention required to fix the underlying error. For example, a UserRecoverableAuthExceptions intent might lead to a request for a user's consent or present the user with a device policy manager download screen. GooglePlayServicesAvailabilityExceptions are UserRecoverableAuthExceptions along with a connection status code which allows clients to create a localized Dialog using getErrorDialog(int, android.app.Activity, int). Finally, this method is blocking and shouldn't be called in the main event thread. If so an IllegalStateException will be thrown.

Which exceptions should be handled and how depends on the context of the code. For example in the case of an Activity where the user is actively engaged:

 String token;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope, bundle);
 } catch (GooglePlayServicesAvailabilityException playEx) {
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
         playEx.getConnectionStatusCode(),
         Activity.this,
         AUTH_REQUEST_CODE);
     // Use the dialog to present to the user.
 } catch (UserRecoverableAutException recoverableException) {
     Intent recoveryIntent = recoverableException.getIntent();
     // Use the intent in a custom dialog or just startActivityForResult.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 
On the other hand, explicitly handling a GooglePlayServicesAvailabilityException in the absence of a UI thread may not be worthwhile. Instead a Notification may be preferable.
 String token;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope, bundle);
 } catch (UserRecoverableAutException recoverableException) {
     Intent recoveryIntent = recoverableException.getIntent();
     // Use the intent to create a Notification.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope.
extras Bundle containing additional information that may be relevant to the authentication scope.
Returns
  • String containing a valid token.
Throws
GooglePlayServicesAvailabilityException containing the appropriate connection status error code.
UserRecoverableAuthException wrapping an Intent for initiating user intervention. The wrapped intent must be called with startActivityForResult(Intent, int).
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalArgumentException if the method is invoked in the main event thread.

public static String getTokenWithNotification (Context context, String accountName, String scope, Bundle extras)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

This method is specifically provided for background tasks. In the event of an error that needs user intervention, this method takes care of pushing relevant notification.

The exception thrown depends upon the underlying error and support for recovery. UserRecoverableNotifiedException will be thrown if the error can be resolved by user intervention and a notification has already been posted to address it. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered programmatically.

 String token;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope, callback, bundle);
 } catch (UserRecoverableNotifiedException userNotifiedException) {
     // Notification has already been pushed.
     // Continue without token or stop background task.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope.
extras Bundle containing additional information that may be relevant to the authentication scope.
Returns
  • String containing a valid token.
Throws
UserRecoverableNotifiedException if a user addressable error occurred and a notification was pushed.
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalArgumentException if the method is invoked in the main event thread.

public static String getTokenWithNotification (Context context, String accountName, String scope, Bundle extras, Intent callback)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

This method is specifically provided for background tasks. In the event of an error that needs user intervention, this method takes care of pushing relevant notification. After the user addresses the notification, the callback is broadcasted. If the user cancels then the callback is not fired.

The exception thrown depends upon the underlying error and support for recovery. UserRecoverableNotifiedException will be thrown if the error can be resolved by user intervention and a notification has already been posted to address it. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered programmatically.

 String token;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope, callback, bundle);
 } catch (UserRecoverableNotifiedException userNotifiedException) {
     // Notification has already been pushed.
     // Continue without token or stop background task.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope.
extras Bundle containing additional information that may be relevant to the authentication scope.
callback A broadcast intent with a valid receiver that has been exported for other apps to send broadcasts to it. This intent must be serializable using toUri(Intent.URI_INTENT_SCHEME) and Intent.parseUri(intentUri, Intent.URI_INTENT_SCHEME). Cannot be null.
Returns
  • String containing a valid token.
Throws
UserRecoverableNotifiedException if a user addressable error occurred and a notification was pushed.
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalArgumentException if the method is invoked in the main event thread.

public static String getTokenWithNotification (Context context, String accountName, String scope, Bundle extras, String authority, Bundle syncBundle)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

This method is specifically provided for sync adaptors. In the event of an error that needs user intervention, this method takes care of pushing relevant notification. After the user addresses the notification, a sync request will be kicked off using the given params. If the user cancels then the sync is not fired.

The exception thrown depends upon the underlying error and support for recovery. UserRecoverableNotifiedException will be thrown if the error can be resolved by user intervention and a notification has already been posted to address it. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered programmatically.

 String token;
 try {
     token = GoogleAuthUtil.getToken(
         context, accountName, scope, authority, syncBundle, bundle);
 } catch (UserRecoverableNotifiedException userNotifiedException) {
     // Notification has already been pushed.
     // Continue without token or stop background task.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope.
extras Bundle containing additional information that may be relevant to the authentication scope.
authority Authority for firing a sync request. Must not be empty or null.
syncBundle extras for firing a sync request. This bundle must pass ContentResolver.validateSyncExtrasBundle(). If no extras are needed can a null value can be passed.
Returns
  • String containing a valid token.
Throws
UserRecoverableNotifiedException if a user addressable error occurred and a notification was pushed.
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalArgumentException if the method is invoked in the main event thread.

public static void invalidateToken (Context context, String token)

Invalidates the specified token with respect to the Context. Note that the context must be the same as that used to initialize the token in a previous call to getToken(Context, String, String) or getToken(Context, String, String, Bundle).

Parameters
context Context of the token.
token String containing the token to invalidate.