How Use Google Drive in Android Studio?

Android, Android Studio

Google Drive is a powerful cloud storage platform that allows you to store and access your files from anywhere. If you are an Android developer using Android Studio, integrating Google Drive into your app can provide seamless file management capabilities to your users. In this tutorial, we will explore how to use Google Drive in Android Studio.

Prerequisites

Before we get started, make sure you have the following:

  • An Android device or emulator running API level 14 or higher.
  • Android Studio installed on your machine.
  • A Google account for accessing Google Drive APIs.

Step 1: Set up a new project in Android Studio

To begin, open Android Studio and create a new project. Choose the minimum SDK version that supports API level 14 or higher.

Select an empty activity template and give your project a name. Click “Finish” to create the project.

Step 2: Set up Google Drive API

To use Google Drive in your app, you need to set up the necessary API credentials.

  1. Go to the Google Developers Console and create a new project.
  2. Navigate to the “Credentials” tab and click on “Create Credentials”. Choose “OAuth client ID” from the dropdown menu.
  3. Select “Android” as the application type and enter your package name.

    Make sure to obtain your package name from your AndroidManifest.xml file in Android Studio.

  4. Add the SHA-1 certificate fingerprint by following the instructions provided by Google. You can generate this fingerprint using keytool or Android Studio.
  5. Click “Create” to generate the OAuth client ID. Take note of the generated client ID as we will need it later.

Step 3: Add Google Drive API dependency

In order to use the Google Drive API in your project, you need to include the necessary dependency in your app’s build.gradle file.

Open your project’s build.gradle file and add the following dependency:


dependencies {
    // other dependencies
    implementation 'com.android.gms:play-services-drive:17.0.0'
}

Step 4: Authenticate with Google Drive API

To access a user’s files on Google Drive, your app needs to authenticate with the Google Drive API using the OAuth client ID we generated earlier.

Add the following code to your MainActivity.java file:


GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(new Scope(DriveScopes.DRIVE_APPDATA))
        .requestEmail()
        .build();

GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this, connectionResult -> {
            // Handle authentication failure
        })
        .addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions)
        .build();

Step 5: Request authorization from user

To request authorization from the user, add the following code to your MainActivity.java file:


Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(signInIntent, REQUEST_CODE_SIGN_IN);

Make sure to handle the result of the authorization request in the onActivityResult method:


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    
    if (requestCode == REQUEST_CODE_SIGN_IN) {
        GoogleSignInResult result = Auth.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // User has authorized your app to access Google Drive
            // Proceed with file operations
        } else {
            // Authorization failed
        }
    }
}

Step 6: Perform file operations on Google Drive

Now that we have authenticated with Google Drive API, we can perform various file operations such as uploading, downloading, and deleting files.

For example, to upload a file to Google Drive, you can use the following code:


DriveFolder driveFolder = Drive.DriveApi.getAppFolder(googleApiClient);

MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
        .setTitle("MyFile.txt")
        .setMimeType("text/plain")
        .build();

ResultCallback callback = new ResultCallback() {
    @Override
    public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult) {
        if (driveFileResult.getStatus().isSuccess()) {
            // File uploaded successfully
        } else {
            // File upload failed
        }
    }
};

driveFolder.createFile(googleApiClient, changeSet, null).setResultCallback(callback);

Similarly, you can use other methods provided by the Google Drive API to perform different file operations.

Conclusion

In this tutorial, we have learned how to integrate Google Drive into your Android Studio project. We covered the steps for setting up the Google Drive API, authenticating with the API, and performing file operations on Google Drive. With this knowledge, you can now leverage the power of Google Drive in your Android applications.

Remember to handle exceptions and implement error handling in your code to ensure a smooth user experience.

Happy coding!