问题
I am able to create a single file in google drive using CreateFileActivity.java.But i want to upload two or more files to the google drive at a time.How is it possible to create multiple files in google drive for android?
回答1:
Assuming, you have multiple files on your Android device, represented by java.io.File objects with known names (titles) and mime type(s):
java.io.File[] files = {...};
String[] names[] = {...};
String[] mimes[] = {...};
You can use this construct to create a set of files in Google drive (in the root, for example):
com.google.android.gms.common.api.GoogleApiClient mGooApiClient;
void foo() {
for (int i = 0; i < files.length; i++) {
createFile(null, names[i], mimes[i], files[i]);
}
}
/***********************************************************************
* create file in GOODrive
* @param pFldr parent's ID, (null for root)
* @param titl file name
* @param mime file mime type
* @param file java.io.File (with content) to create
*/
void createFile(DriveFolder pFldr, final String titl, final String mime, final File file) {
DriveId dId = null;
if (mGooApiClient != null && mGooApiClient.isConnected() && titl != null && mime != null && file != null) try {
final DriveFolder parent = pFldr != null ? pFldr : Drive.DriveApi.getRootFolder(mGooApiClient);
if (pFldr == null) return; //----------------->>>
Drive.DriveApi.newDriveContents(mGAC).setResultCallback(new ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult driveContentsResult) {
DriveContents cont = driveContentsResult != null && driveContentsResult.getStatus().isSuccess() ?
driveContentsResult.getDriveContents() : null;
if (cont != null) try {
OutputStream oos = cont.getOutputStream();
if (oos != null) try {
InputStream is = new FileInputStream(file);
byte[] buf = new byte[4096];
int c;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
}
finally { oos.close();}
MetadataChangeSet meta = new Builder().setTitle(titl).setMimeType(mime).build();
parent.createFile(mGooApiClient, meta, cont).setResultCallback(new ResultCallback<DriveFileResult>() {
@Override
public void onResult(DriveFileResult driveFileResult) {
DriveFile dFil = driveFileResult != null && driveFileResult.getStatus().isSuccess() ?
driveFileResult.getDriveFile() : null;
if (dFil != null) {
// save dFil, report success
} else {
// handle error
}
}
});
} catch (Exception e) {e.printStackTrace();}
}
});
} catch (Exception e) { e.printStackTrace(); }
}
Don't forget to save the DriveFile (or DriveId) or the created files.
Good Luck
来源:https://stackoverflow.com/questions/33517043/how-to-create-multiple-files-programmatically-using-drive-api-for-android