Setup Android Google Drive Api

May 21, 2018

NOTE: Google Drive Android API is deprecated on December 6, 2018 and will no longer work on December 6, 2019. Refer to the latest Android Google Drive REST API tutorial.

Google Play Services

Set Up Google Play Services.

Edit app module’s build.gradle.

dependencies {
    // https://developers.google.com/android/guides/releases
    implementation "com.google.android.gms:play-services-auth:15.0.0"
    implementation "com.google.android.gms:play-services-drive:15.0.0"
}

Connecting and Authorizing the Google Drive Android API

You need to create a Google APIs project.

Use keytool to get the SHA1 fingerprint of your apk.

keytool -exportcert -keystore {keystore.jks} -alias {alias_name} -list -v
Enter keystore password:
Alias name: ***
Creation date: Apr 2, 2018
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: O=Lua Software
Issuer: O=Lua Software
Serial number: 7089fffe
Valid from: Mon Apr 02 19:15:54 SGT 2018 until: Tue Mar 09 19:15:54 SGT 2117
Certificate fingerprints:
         MD5:  38:A3:***
         SHA1: DF:C2:***
         SHA256: 42:E1:***
         Signature algorithm name: SHA256withRSA
         Version: 3

NOTE: Refer to Get SHA-1 Fingerprint Of Keystore Certificate (*.jks for Windows) to get SHA-1 Fingerprint for both development/debug and production app.

Open Google APIs - Credentials -> Create credentials -> OAuth Client ID -> Android. Put in package name and SHA1 fingerprint, then click Create.

Google API Credential - OAuth Client ID

NOTE: I believe the OAuth Client ID is not used for our use case.

Make sure Google Drive API is enabled in Google APIs - Library.

Code

The following code allow user to signin to Google Drive account to get access to DriveClient and DriveResourceClient.

class BackupActivity : AppCompatActivity() {
    companion object {
        private const val GOOGLE_SIGNIN_BACKUP_REQUEST_CODE = 1
    }

    private lateinit var googleSignInClient: GoogleSignInClient
    private var driveClient: DriveClient? = null
    private var driveResourceClient: DriveResourceClient? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == GOOGLE_SIGNIN_BACKUP_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this)
                driveClient = googleSignInAccount?.let { Drive.getDriveClient(this, it) }
                driveResourceClient = googleSignInAccount?.let { Drive.getDriveResourceClient(this, it) }

                // do something
            }
            else {

            }
        }
    }

    private fun buildGoogleSignInClient(): GoogleSignInClient {
        val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
              .requestScopes(Drive.SCOPE_FILE)
              // .requestScopes(Drive.SCOPE_APPFOLDER)
              .build()
        return GoogleSignIn.getClient(this, signInOptions)
    }

    private fun signIn() {
        googleSignInClient = buildGoogleSignInClient()
        startActivityForResult(googleSignInClient.signInIntent, GOOGLE_SIGNIN_BACKUP_REQUEST_CODE)
    }

    private fun signOut() {
        googleSignInClient.signOut()
    }
}

Refer to Google Drive APIs - Files and Folders on how to create, read and delete files and folders using Google Drive API.

You can also refer to Android Google Drive API Storing App Data (Like WhatsApp Google Drive Backup & Restore).

Proguard

Edit proguard-rules.pro

# Fix OAuth Drive API failure for release builds
-keep class * extends com.google.api.client.json.GenericJson { *; }
-keep class com.google.api.services.drive.** { *; }
-keepclassmembers class * { @com.google.api.client.util.Key <fields>; }

to avoid the following error

403 Forbidden { "errors" : [ { "domain" : "usageLimits", "reason" : "dailyLimitExceededUnreg", "message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "extendedHelp" : "https://code.google.com/apis/console" } ], "code" : 403, "message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." }

NOTE: Thanks CmosBattery for the solution.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.