If you are trying to upload a file and share it with another account at the same time, you need to wait a few seconds before performing the permissions request. I could achieve it in my Android app like this (using Kotlin and RxJava):
private fun uploadFile(accessToken: String, fileName: String, fileContent: String) {
Observable.just(Unit)
.subscribeOn(Schedulers.io())
.subscribe({
val httpTransport = NetHttpTransport()
val credential = Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
.build()
credential.accessToken = accessToken
val service = Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName("Your App Name")
.build()
val fileMetadata = File()
fileMetadata.name = fileName
val localFile = createFile(fileName, fileContent)
val mediaContent = InputStreamContent("text/plain", localFile);
val file = service.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute()
Log.d(TAG, "File ID: " + file.id)
Observable.interval(10, TimeUnit.SECONDS)
.take(1)
.subscribe {
val callback = object : JsonBatchCallback<Permission>() {
@Throws(IOException::class)
override fun onFailure(e: GoogleJsonError, responseHeaders: HttpHeaders) {
Log.d(TAG, "error: ${e.message}")
}
@Throws(IOException::class)
override fun onSuccess(permission: Permission, responseHeaders: HttpHeaders) {
Log.d(TAG, "Permission ID: ${permission.id}")
}
}
val batch = service.batch()
val userPermission = Permission()
.setType("user")
.setRole("writer")
.setEmailAddress("[email protected]")
service.permissions().create(file.id, userPermission)
.setFields("id")
.queue(batch, callback)
batch.execute()
}
}) {
Log.d(TAG, "error: ", it)
}
}
private fun createFile(fileName: String, fileContent: String): InputStream? {
try {
val outputStreamWriter = OutputStreamWriter(
application.openFileOutput(fileName, Context.MODE_PRIVATE))
outputStreamWriter.write(fileContent)
outputStreamWriter.close()
return application.openFileInput(fileName)
} catch (e: IOException) {
Log.e(TAG, "File write failed: ", e)
}
return null
}
sometimes I'm unable to share file with him.? Although you shared your file to user "A", the file was not shared and user "A" couldn't access to the file. Is my understanding correct? - Tanaike