到目前为止,我一直在使用上传文件来驱动演示代码。但是,对于我的应用程序,我需要能够通过单击按钮上传多个用户选择的文件。我的问题是,它不会将每个文件上传到云端硬盘,而是会为每个选定的文件上传最后一个选定的文件。我想如果我理解正确的话,这与 IntentSender 快速执行多次并返回REQUEST_CODE_CREATOR
案例有关,但我看不到另一种构建代码的方法。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_LAUNCH_MAIN:
if (resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
for (int i = 0; i<bundle.size()/2; i++) {
file = bundle.getByteArray(DATA+i);
directory = new Directory(bundle.getString(PATH+i));
Log.i(TAG, bundle.getString(PATH+i) + " extracted");
uploadFileToDrive();
Log.i(TAG, bundle.getString(PATH+i) + " uploaded");
}
}
Toast.makeText(this, "Finished Uploading", 0).show();
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Files successfully saved.");
Toast.makeText(this, "Starting new process", 0).show();
file = null;
// Return to the Main UI to select more apps ect.
startActivityForResult(new Intent(this, MainActivity.class),
REQUEST_CODE_LAUNCH_MAIN);
}
break;
}
}
uploadToDrive()
方法
public void uploadFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newContents(googleApiClient).setResultCallback(new ResultCallback<DriveApi.ContentsResult>() {
@Override
public void onResult(DriveApi.ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
Log.i(TAG, "New contents created.");
OutputStream outputStream = result.getContents().getOutputStream();
try {
outputStream.write(file);
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("application/zip")
.setTitle(directory.getZipFileName())
.build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(googleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}