I’m working on an Android app that needs to upload video files to Google Drive. I can already record videos using camera intents and save them to device storage, but I’m stuck on the upload part.
I found Google’s quickstart example for uploading images, but I need to modify it for video files instead. The main difference should be handling video data rather than bitmap data, but I’m not sure about the exact implementation.
Here’s a modified version of what I’m trying to achieve:
/**
* Video upload activity for Google Drive integration
*/
public class VideoUploadActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String LOG_TAG = "video-drive-upload";
private static final int VIDEO_CAPTURE_REQUEST = 100;
private static final int FILE_CREATOR_REQUEST = 200;
private static final int CONNECTION_RESOLUTION_REQUEST = 300;
private GoogleApiClient driveApiClient;
private Uri videoFileUri;
private void uploadVideoToDrive() {
Log.d(LOG_TAG, "Starting video upload process.");
final Uri videoUri = videoFileUri;
Drive.DriveApi.newDriveContents(driveApiClient)
.setResultCallback(new ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult uploadResult) {
if (!uploadResult.getStatus().isSuccess()) {
Log.e(LOG_TAG, "Could not create drive contents.");
return;
}
Log.d(LOG_TAG, "Drive contents ready for upload.");
OutputStream driveOutputStream = uploadResult.getDriveContents().getOutputStream();
try {
InputStream videoInputStream = getContentResolver().openInputStream(videoUri);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = videoInputStream.read(buffer)) != -1) {
driveOutputStream.write(buffer, 0, bytesRead);
}
videoInputStream.close();
} catch (IOException ex) {
Log.e(LOG_TAG, "Error writing video data.");
}
MetadataChangeSet videoMetadata = new MetadataChangeSet.Builder()
.setMimeType("video/mp4")
.setTitle("RecordedVideo.mp4")
.build();
IntentSender fileChooserIntent = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(videoMetadata)
.setInitialDriveContents(uploadResult.getDriveContents())
.build(driveApiClient);
try {
startIntentSenderForResult(
fileChooserIntent, FILE_CREATOR_REQUEST, null, 0, 0, 0);
} catch (SendIntentException ex) {
Log.e(LOG_TAG, "Could not start file chooser.");
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
switch (requestCode) {
case VIDEO_CAPTURE_REQUEST:
if (resultCode == Activity.RESULT_OK) {
videoFileUri = resultData.getData();
uploadVideoToDrive();
}
break;
case FILE_CREATOR_REQUEST:
if (resultCode == RESULT_OK) {
Log.d(LOG_TAG, "Video upload completed successfully.");
videoFileUri = null;
}
break;
}
}
}
Is this the right approach for handling video uploads? Any suggestions on how to properly stream video data to Google Drive would be really helpful!