我正在开发Android应用程序,使用Google Drive分享内容给朋友。所以有可能在Android中使用谷歌驱动程序以编程方式共享文件吗?
答案 0 :(得分:2)
是的,如果您在应用中未包含标准共享功能但想要专门上传到Google云端硬盘,那么您将不得不使用Google云端硬盘API。它有点复杂,所以我不会发布完整的解决方案,但我会告诉你重要的部分。我建议你看看其中一个示例项目:
但无论如何,这里有重要的部分:
首先,您必须创建一个类似于此的API客户端:
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this);
// Add Drive API
mGoogleApiClient.addApi(Drive.API);
// Set Scope
mGoogleApiClient.addScope(Drive.SCOPE_FILE);
// Add required callbacks
mGoogleApiClient.addConnectionCallbacks(this);
mGoogleApiClient.addOnConnectionFailedListener(this);
// Build client
mGoogleApiClient.build();
使用此API客户端,您可以上传/下载/移动/复制/删除文件和文件夹等。
上传文件看起来像这样:
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback<ContentsResult>() {
@Override
public void onResult(ContentsResult result) {
// Check for success
if (!result.getStatus().isSuccess()) {
return;
}
// Upload file
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.", e);
}
// Set meta data
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder();
metadataChangeSet.setMimeType("image/jpeg");
metadataChangeSet.setTitle("Android Photo.png");
metadataChangeSet.build();
// Create file chooser
IntentSender intentSender = Drive.DriveApi.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
// Show file chooser
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.", e);
}
}
});
答案 1 :(得分:-1)
使用Google Drive API for Java完成Google云端硬盘共享,如下所示
googleDrive.permissions.insert(许可);
答案 2 :(得分:-1)
Permission newPermission = new Permission();
newPermission.setValue(emailvalue);
newPermission.setType(type);
newPermission.setRole(role);
try {
service.permissions().insert(fid, newPermission).execute();
showToast("Done Shared successfully!!!!!!");
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}