Android:上传至Google Drive?
创始人
2024-10-13 18:30:24
0

在Android应用中上传文件至Google Drive,可以使用Google Drive API来实现。下面是一个示例代码,展示了如何上传文件至Google Drive。

首先,确保在项目的build.gradle文件中添加了Google Drive API的依赖:

implementation 'com.google.android.gms:play-services-drive:17.0.0'

然后,在你的Activity或Fragment中添加以下代码:

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_SIGN_IN = 1;

    private DriveClient driveClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 配置Google Sign-In
        GoogleSignInOptions signInOptions =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .requestScopes(Drive.SCOPE_FILE)
                        .build();
        GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);

        // 启动Google Sign-In Intent
        startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_SIGN_IN) {
            if (resultCode == RESULT_OK) {
                // Google Sign-In 成功
                handleSignInResult(data);
            } else {
                // Google Sign-In 失败
                // 处理失败情况
            }
        }
    }

    private void handleSignInResult(Intent data) {
        Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            // 使用Google账户初始化DriveClient
            driveClient = Drive.getDriveClient(this, account);
            // 上传文件至Google Drive
            uploadFileToDrive();
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    private void uploadFileToDrive() {
        // 创建一个新的文件
        final Task rootFolderTask = driveClient.getRootFolder();
        final Task createContentsTask = driveClient.createContents();

        Tasks.whenAll(rootFolderTask, createContentsTask)
                .continueWithTask(task -> {
                    DriveFolder parent = rootFolderTask.getResult();
                    DriveContents contents = createContentsTask.getResult();

                    // 将文件内容写入DriveContents
                    OutputStream outputStream = contents.getOutputStream();
                    try {
                        InputStream inputStream = getContentResolver().openInputStream(fileUri);
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    // 设置文件的元数据
                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                            .setTitle("MyFile.txt")
                            .setMimeType("text/plain")
                            .setStarred(true)
                            .build();

                    // 创建文件
                    return driveClient.createFile(parent, changeSet, contents);
                })
                .addOnCompleteListener(this, new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()) {
                            // 文件上传成功
                            DriveFile file = task.getResult();
                            String fileId = file.getDriveId().encodeToString();
                            Log.d("MainActivity", "File uploaded: " + fileId);
                        } else {
                            // 文件上传失败
                            Exception e = task.getException();
                            e.printStackTrace();
                        }
                    }
                });
    }
}

上述代码中,handleSignInResult()方法处理Google Sign-In的结果,获得用户的Google账户,并初始化DriveClientuploadFileToDrive()方法创建一个新的文件,并将文件内容写入DriveContents,然后设置文件的元数据,并最终创建文件并上传至Google Drive。

注意,上述代码中的fileUri

相关内容

热门资讯

据统计!pokemomo辅助软... 据统计!pokemomo辅助软件,八张透视辅助,演示教程(有挂细节)1、全新机制【八张透视辅助ai辅...
明白辅助挂!红龙poker作弊... 明白辅助挂!红龙poker作弊指令,奇迹脚本辅助,大纲教程(有挂方针)1、游戏颠覆性的策略玩法,独创...
目前!德州圈脚本,德普之星辅助... 目前!德州圈脚本,德普之星辅助器,积累教程(真的有挂)1、操作简单,无需德普之星辅助器手机版透视脚本...
相较于以往!智星菠萝有挂吗,来... 相较于以往!智星菠萝有挂吗,来来拼十辅助免费辅助,方针教程(存在有挂)1、首先打开来来拼十辅助免费辅...
据通报!德扑之心免费透视,广东... 据通报!德扑之心免费透视,广东雀神挂机怎么样,步骤教程(有挂方略)1、该软件可以轻松地帮助玩家将广东...
有玩家发现!aapoker真的... 有玩家发现!aapoker真的假的,闲聚辅助器,绝活儿教程(讲解有挂)1)闲聚辅助器免费钻石:进一步...
方法辅助挂!德州局脚本,博雅红... 方法辅助挂!德州局脚本,博雅红河西元红河挂,方式教程(有挂讲解)1、博雅红河西元红河挂免费辅助多个强...
有玩家发现!扑克之星辅助,jj... 有玩家发现!扑克之星辅助,jj斗地主外卦,讲义教程(有挂分析)1、进入到jj斗地主外卦是否有挂之后,...
黑科技辅助挂!hhpoker辅... 黑科技辅助挂!hhpoker辅助,陕麻圈辅助开挂软件,妙招教程(有挂详情);1、下载好陕麻圈辅助开挂...
为切实保障!epoker透视底... 为切实保障!epoker透视底牌,哈局八张辅助,总结教程(有挂方略)1、该软件可以轻松地帮助玩家将哈...