我只想将文件上传到Google云端硬盘

时间:2018-08-01 09:11:16

标签: android google-drive-android-api

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

但是无法上传现有文件。

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

谢谢

2 个答案:

答案 0 :(得分:0)

您可能要检查Google Drive Android API,以了解如何管理文件内容和元数据。您可以使用Drive Android API通过两种方式创建文件:使用DriveClient.newCreateFileActivityIntentSender方法和CreateFileActivityOptions类;或使用DriveResourceClient.createFile方法。

您还可以检查以下链接以获取其他参考:

答案 1 :(得分:-1)

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
            }
        })
    }
}