Certainly! Below is a Kotlin code snippet that demonstrates how to use androidx.credentials.CredentialManager to handle Google Sign-In and subsequently upload a file to Google Drive.
Step 1: Add Dependencies
First, ensure you have the necessary dependencies in your build.gradle file:
dependencies {
implementation "androidx.credentials:credentials:1.0.0-alpha05"
implementation 'com.google.android.gms:play-services-auth:20.2.0'
implementation 'com.google.api-client:google-api-client:1.32.1'
implementation 'com.google.api-client:google-api-client-android:1.32.1'
implementation 'com.google.apis:google-api-services-drive:v3-rev20210201'
}
Step 2: Configure Google Sign-In
Add the following to your AndroidManifest.xml:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.libraries.fitness.API_KEY"
android:value="YOUR_API_KEY" />
Step 3: Kotlin Code
Here's the Kotlin code to handle Google Sign-In and upload a file to Google Drive:
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.credentials.CredentialManager
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetCredentialResponse
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.api.client.extensions.android.http.AndroidHttp
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.drive.Drive
import com.google.api.services.drive.model.File
import java.io.File as JavaFile
class MainActivity : AppCompatActivity() {
private lateinit var googleSignInClient: GoogleSignInClient
private val RC_SIGN_IN = 9001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
signIn()
}
private fun signIn() {
val signInIntent: Intent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
val account: GoogleSignInAccount? = completedTask.getResult(ApiException::class.java)
// Signed in successfully, show authenticated UI.
account?.let {
uploadFileToDrive(it)
}
} catch (e: ApiException) {
// The ApiException status code indicates the detailed failure reason.
Toast.makeText(this, "Google sign in failed", Toast.LENGTH_SHORT).show()
}
}
private fun uploadFileToDrive(account: GoogleSignInAccount) {
val credential: GoogleAccountCredential = GoogleAccountCredential.usingOAuth2(
this, listOf(DriveScopes.DRIVE)
).setBackOff(ExponentialBackOff())
credential.selectedAccount = account.account
val driveService: Drive = Drive.Builder(
AndroidHttp.newCompatibleTransport(),
GsonFactory(),
credential
).setApplicationName("Your App Name").build()
val fileMetadata = File().setParents(listOf("root")).setName("Test File")
val fileContent = JavaFile("path/to/your/file")
val mediaContent = FileContent("text/plain", fileContent)
try {
val file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute()
Toast.makeText(this, "File uploaded: ${file.id}", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Toast.makeText(this, "An error occurred: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
}
Explanation
-
Google Sign-In Configuration:
- Configure Google Sign-In options and create a
GoogleSignInClient.
- Initiate the sign-in flow and handle the result in
onActivityResult.
-
Uploading to Google Drive:
- Once signed in, use the
GoogleSignInAccount to create a GoogleAccountCredential.
- Initialize the
Drive service and upload a file.
Note
- Replace
"path/to/your/file" with the actual path to the file you want to upload.
- Ensure you have the appropriate OAuth consent screen and API access configured in the Google Cloud Console.
This code provides a basic implementation. You may need to handle additional edge cases and errors based on your specific requirements.