谷歌驱动器上传和下载服务作为背景

时间:2013-01-30 14:08:05

标签: android google-drive-api

我可以使用Android手机中添加的帐户上传到Google云端硬盘。我按照http://www.youtube.com/watch?v=Ied1CjJ0iP0中的步骤操作。我真正想做的是通过服务作为后台进程从多部手机上传到一个帐户。我该怎么办呢。

1 个答案:

答案 0 :(得分:0)

我首先使用片段中的常规方法登录

    private fun upload() {
        Log.i(TAG, "Start sign in")
        val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(Drive.SCOPE_FILE)
            .build()
        val googleSignInClient = GoogleSignIn.getClient(this.requireActivity(), signInOptions)

        startActivityForResult(googleSignInClient.signInIntent, MyFragment.REQUEST_CODE_SIGN_IN)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            MyFragment.REQUEST_CODE_SIGN_IN -> {
            if (resultCode == Activity.RESULT_OK) {
                 Log.i(TAG, "Signed into drive ok.")

                 //Create an intent for starting the service
                 //Add whatever data you need to the intent
                 val intent = Intent(context, UploadService::class.java)
                 requireContext().startService(intent)
            }
        }
    }

然后在UploadService中

override fun onHandleIntent(intent: Intent?) {
    if (intent == null) {
        return
    }

    val lastSignedInAccount = GoogleSignIn.getLastSignedInAccount(this) ?: throw IllegalStateException("Not logged in")
    val driveClient = Drive.getDriveClient(this, lastSignedInAccount)
    val driveResourceClient = Drive.getDriveResourceClient(this, lastSignedInAccount)

    .... Do what you need to do here
}

请记住将服务添加到您的AndroidManifest.xml

 <service
        android:name=".UploadService"
        android:enabled="true"
        android:exported="false" />
相关问题