Authorizing Android Apps

Authorizing requests on Android differs from other authorization workflows because of the integration with Google Play services. Unlike other workflows, authorization on Android uses a SHA1 fingerprint and package name to identify your app instead of a client ID and client secret.

For an example of authorization with Android, see the Android Quickstart. For more information on Android development, see the Android documentation.

Generate the signing certificate fingerprint and register your application

If you haven't already registered your application with the Google API Console, then set up a project and application in the API Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the API Console, then follow this procedure instead:

In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file's public certificate.
keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

The Keytool prints the fingerprint to the shell. For example:

$ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
Enter keystore password: Type "android" if using debug.keystore
Alias name: androiddebugkey
Creation date: Aug 27, 2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 503bd581
Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
Certificate fingerprints:
   MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
   SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
   SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
   Signature algorithm name: SHA1withRSA
   Version: 3

Copy the SHA1 fingerprint, which is highlighted in the example above.

Next, create credentials appropriate to your project in the Google API Console:

  1. Open the Credentials page in the API Console.
  2. Follow these steps if your application needs to submit authorized requests:

    1. Click Create credentials > OAuth client ID.
    2. Select Android.
    3. In the Package name field, enter your Android app's package name.
    4. Paste the SHA1 fingerprint into the form where requested.
    5. Click Create.

    Otherwise, follow the steps below, which are for applications that only need to make unauthorized API calls:

    1. Click Create credentials > API key.
    2. Select Android key.
    3. Paste the SHA1 fingerprint into the form where requested.
    4. Type your Android app's package name into the form where requested.
    5. Click Create.

Connecting and Authorizing the Google Drive Android API

Authorization for the Google Drive Android API is handled by the GoogleSignInClient. This is typically created in an activity's onCreate() method.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstance);
    mGoogleSignInClient = buildGoogleSignInClient();

    // Other code ...
}

private GoogleSignInClient buildGoogleSignInClient() {
  GoogleSignInOptions signInOptions =
      new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
          .requestScopes(Drive.SCOPE_FILE)
          .build();
  return GoogleSignIn.getClient(this, signInOptions);
}

To get the account for the current user, you need to call GoogleSignInClient.getGoogleSignInAccountFromIntent() The getGoogleSignInAccountFromIntent() method returns a Task object. In the success handler for the Task object, you can access the GoogleSignInAccount associated with the current user.

Once you have the GoogleSignInAccount object, you can then create an instance of the DriveClient and DriveResourceClient classes, which allow you to access the contents of the user's Drive.

The following code snippet demonstrates one technique for accessing a GoogleSignInAccount from the success listener of a Task object. It also demonstrates how to instantiate a DriveClient and DriveResourceClient object after sign-in has succeeded.

private void updateViewWithGoogleSignInAccountTask(Task<GoogleSignInAccount> task) {
  Log.i(TAG, "Update view with sign in account task");
  task.addOnSuccessListener(
          new OnSuccessListener<GoogleSignInAccount>() {
            @Override
            public void onSuccess(GoogleSignInAccount googleSignInAccount) {
              Log.i(TAG, "Sign in success");
              // Build a drive client.
              mDriveClient = Drive.getDriveClient(getApplicationContext(), googleSignInAccount);
              // Build a drive resource client.
              mDriveResourceClient =
                  Drive.getDriveResourceClient(getApplicationContext(), googleSignInAccount);
              // Start camera.
              startActivityForResult(
                  new Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_CODE_CAPTURE_IMAGE);
            }
          })
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              Log.w(TAG, "Sign in failed", e);
            }
          });
}

Connecting and Authorizing with the Google APIs Java Client

In some cases, applications may need to use the Google Drive web service to access additional features or access broader scopes than what is available in the Google Drive Android API. In these cases, your application must use the Google APIs Client Library for Java.

This code sample demonstrates instantiating the Drive service to send requests. Note that at this point, you have not yet authenticated the user's credentials or requested authorization to access their Drive files.

GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
credential.setSelectedAccountName(accountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();

Authorization happens in response to receiving an error when sending a request. Your app must be prepared to catch the UserRecoverableAuthIOException. This means the user needs to authorize the app.

The following code sample demonstrates how to handle this exception.

try {
    // Try to perform a Drive API request, for instance:
    // File file = service.files().insert(body, mediaContent).execute();
} catch (UserRecoverableAuthIOException e) {
    startActivityForResult(e.getIntent(), COMPLETE_AUTHORIZATION_REQUEST_CODE);
}

Upon completion, your app should either go back to sending the request (user granted access), allow the user to select an alternate account, or display an appropriate message.

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
        ...
        case COMPLETE_AUTHORIZATION_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                // App is authorized, you can go back to sending the API request
            } else {
                // User denied access, show him the account chooser again
            }
            break;
    }
}

Next steps

Now that your application is authorized, you can create and open files and folders, or query for files.

Send feedback about...

Drive API for Android
Drive API for Android