Integrate Google Drive For Backup data on android Kotlin Jetpack Compose

salman dev
4 min readJan 14, 2024

--

Hi guys In this is my first article In this article I will show you how to integrate google drive to save data and restore it.

You can see video

https://www.youtube.com/watch?v=OgBsMl1dw10

Add the following dependencies to your app level gradle

implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
implementation("com.google.firebase:firebase-analytics")
implementation ("com.google.android.gms:play-services-auth:20.7.0")
implementation ("com.google.firebase:firebase-auth")
implementation ("com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0")
implementation ("com.google.api-client:google-api-client:2.0.0")
implementation ("com.google.api-client:google-api-client-android:1.32.1")
implementation ("com.google.oauth-client:google-oauth-client-jetty:1.34.1")
implementation ("com.google.auth:google-auth-library-oauth2-http:1.19.0")

Also add these plugins

    kotlin("kapt")
id("com.google.dagger.hilt.android")
id("com.google.gms.google-services")

on gradle project also add these

    id("com.google.dagger.hilt.android") version "2.48" apply false
id("com.google.gms.google-services") version "4.4.0" apply false

First we need firebase project for using google sign in. I choose firebase because it’s so easy implement authentication google sign in on authentication page go to sign in method and click to google then web SDK configuration and copy your web client ID see image

then add your SHA get from android studio in gradle tasks

we use Identity API for easy request google sign in then create fun that returned intentSender to use on Activity Result

private val oneTap = Identity.getSignInClient(context)
private val signInRequest = BeginSignInRequest.builder().setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder().setSupported(true)
.setServerClientId(
"your web client ID"
).setFilterByAuthorizedAccounts(false).build()
).setAutoSelectEnabled(true).build()

override suspend fun signInGoogle(): IntentSender {
return oneTap.beginSignIn(signInRequest).await().pendingIntent.intentSender
}
 val signInLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult(),
onResult = {
viewModel.onEvent(MainEvent.OnSignInResult(it.data?:return@rememberLauncherForActivityResult))
}
)

After sign in we must authorize to google drive access


private val authorize = Identity.getAuthorizationClient(context)
private val authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(scopes).build()



// request authorize after sign in
override suspend fun authorizeGoogleDrive(): AuthorizationResult {
return authorize.authorize(authorizationRequest).await()
}

override suspend fun authorizeGoogleDriveResult(intent: Intent): AuthorizationResult {
return authorize.getAuthorizationResultFromIntent(intent)
}

Now we are ready to use Drive API. Let’s implement some features we can upload any files on google drive for now I will upload photo to google drive

suspend fun decodeImage(uri: Uri, context: Context):File{
return withContext(Dispatchers.IO){
val contentResolver = context.contentResolver
val file = File(context.filesDir,"testImage.png")
val fileOutput = FileOutputStream(file)
val btm = ImageDecoder.createSource(contentResolver,uri).decodeBitmap { info, source ->
}
btm.compress(Bitmap.CompressFormat.WEBP_LOSSY,80,fileOutput)
file
}
}

we get Uri Image from PhotoPicker Api it returns uri image when pick. After that we decode it in file then we upload photo to google drive

suspend fun backupImage(
drive: Drive,
file: File,
fileName:String
){
withContext(Dispatchers.IO){
val fileG = com.google.api.services.drive.model.File().apply {
name = fileName
}

val mediaContent = FileContent("image/jpeg",file)
drive.files().create(fileG,mediaContent).execute()
}
}

Now let’s get files that we upload to google drive

suspend fun getAllBackupFiles(drive: Drive): List<DriveFileInfo> {
val files = mutableListOf<DriveFileInfo>()
return withContext(Dispatchers.IO) {
val result =
drive.files().list().setSpaces("drive").setFields("*")
.execute()
files.addAll(result.files.map { DriveFileInfo(it.id, it.name, getFileSize(it.getSize()),it.thumbnailLink) })
files
}
}

now let’s restore file to local storage using this code

suspend fun getDriveFileById(drive: Drive,fileId: String):ByteArray{
val byteArray = ByteArrayOutputStream()
drive.files().get(fileId).executeMediaAndDownloadTo(byteArray)
return byteArray.toByteArray()
}

// to save in local storage
suspend fun saveImageToLocalStorage(imageByteArray: ByteArray){
val btm = BitmapFactory.decodeByteArray(imageByteArray,0,imageByteArray.size)
context.openFileOutput(UUID.randomUUID().toString(),Context.MODE_PRIVATE).use {
btm.compress(Bitmap.CompressFormat.WEBP_LOSSY,80,it)
}
}

and that’s all for now there are a lot features that you can use with google drive but for now we just implement upload and resotre files

Github project : https://github.com/salmanA169/IntegrateGoogleDrive

Thank you

Connect me on :)

• Linkedin — https://www.linkedin.com/in/salman-saleh-42bb3215b/
• Instgtram—https://www.instagram.com/_salman.saleh/
• Github — https://github.com/salmanA169/IntegrateGoogleDrive
• X— https://twitter.com/salmandev6

--

--