我只想将文件上传到 Google 驱动器

I only want to upload files to Google Drive

有一种方法可以创建文件并将其上传到官方 Google 文档和演示源。

但是无法上传现有文件。

我想知道如何将 Android 应用程序的文件(例如 Sqlite 数据库文件)上传到 Google 云端硬盘。

谢谢

您可能需要检查 Google Drive Android API on how to manage file content and metadata. You can create files in two ways with the Drive Android API: using the DriveClient.newCreateFileActivityIntentSender method and the CreateFileActivityOptions class; or using the DriveResourceClient.createFile 方法。

您还可以查看这些链接以获取更多参考:

  • How to upload a db file to google drive from android application?
  • Android Open and Save files to/from Google Drive SDK
  • How to upload a file to Google Drive
private fun handleSignInIntent(resultIntent: Intent) {
    GoogleSignIn.getSignedInAccountFromIntent(resultIntent)
        .addOnSuccessListener {
            Toast.makeText(this, "Sign-in Successful!!", Toast.LENGTH_LONG).show()
            val credentials = GoogleAccountCredential.usingOAuth2(
                this,
                Collections.singleton(DriveScopes.DRIVE_FILE)
            )
            credentials.selectedAccount = it.account
            val drive =
                Drive.Builder(AndroidHttp.newCompatibleTransport(), GsonFactory(), credentials)
                    .setApplicationName("DB BackUp").build()

            driveServiceHelper=DriveServiceHelper(drive)
        }
        .addOnFailureListener {
            Toast.makeText(this, "Sign-in Failed!!", Toast.LENGTH_LONG).show()
        }
    }

// Drive Service Helper class : 
class DriveServiceHelper(private val driveService: Drive) {
    private val executor = Executors.newSingleThreadExecutor()

    fun createFile(filePath: String): Task<String> {
        return Tasks.call(executor,object : Callable<String>{
            override fun call(): String {
                val fileMetadata=File()
                fileMetadata.name="BACKUP_SAMPLE"

                val fileToUpload = java.io.File(filePath)

                val mediaContent = FileContent("*/*", fileToUpload)

                var myFile = File()
                try {
                    myFile=driveService.files().create(fileMetadata, mediaContent).execute()
                } catch (e:Exception){
                    Log.e("DriveException>>", "${e.message} <<<")
                }

                if (myFile==null)
                    throw IOException("Null file received on Creation")

                return myFile.id
            }
        })
    }
}