简体   繁体   English

Android Studio和Google Drive API(将视频上传到Google Drive)

[英]Android Studio and Google Drive API (Uploading video to Google Drive)

I followed the quickstart guide from Google to take an image and afterwards upload it to the users Google Drive. 我按照Google的快速入门指南进行拍摄,然后将其上传到用户Google云端硬盘。

My question is, how can i adapt this to using video and uploading video to Google Drive instead of an image? 我的问题是,我该如何适应使用视频并将视频而非图像上传到Google云端硬盘? I already know how to access and record video's using intents (and saving it on the external storage) but not how to upload afterwards. 我已经知道如何使用意图来访问和记录视频(并将其保存在外部存储中),但后来却不知道如何上传。 My guess is it would be pretty much the same as the following code, but again not sure. 我的猜测是,它将与以下代码几乎相同,但同样不确定。

Any help will be appreciated! 任何帮助将不胜感激!

/**
 * Android Drive Quickstart activity. This activity takes a photo and saves it
 * in Google Drive. The user is prompted with a pre-made dialog which allows
 * them to choose the file location.
 */
public class Main2Activity extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener {

    private static final String TAG = "drive-quickstart";
    private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
    private static final int REQUEST_CODE_CREATOR = 2;
    private static final int REQUEST_CODE_RESOLUTION = 3;

    private GoogleApiClient mGoogleApiClient;
    private Bitmap mBitmapToSave;


    /**
     * Create a new file and save it to Drive.
     */

    private void saveFileToDrive() {
        // Start by creating a new contents, and setting a callback.
        Log.i(TAG, "Creating new contents.");
        final Bitmap image = mBitmapToSave;
        Drive.DriveApi.newDriveContents(mGoogleApiClient)
                .setResultCallback(new ResultCallback<DriveContentsResult>() {

                    @Override
                    public void onResult(DriveContentsResult result) {
                        // If the operation was not successful, we cannot do anything
                        // and must
                        // fail.
                        if (!result.getStatus().isSuccess()) {
                            Log.i(TAG, "Failed to create new contents.");
                            return;
                        }
                        // Otherwise, we can write our data to the new contents.
                        Log.i(TAG, "New contents created.");
                        // Get an output stream for the contents.
                        OutputStream outputStream = result.getDriveContents().getOutputStream();
                        // Write the bitmap data from it.
                        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.");
                        }
                        // 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("image/jpeg").setTitle("Android Photo.png").build();
                        // Create an intent for the file chooser, and start it.
                        IntentSender intentSender = Drive.DriveApi
                                .newCreateFileActivityBuilder()
                                .setInitialMetadata(metadataChangeSet)
                                .setInitialDriveContents(result.getDriveContents())
                                .build(mGoogleApiClient);
                        try {
                            startIntentSenderForResult(
                                    intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                        } catch (SendIntentException e) {
                            Log.i(TAG, "Failed to launch file chooser.");
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            // Create the API client and bind it to an instance variable.
            // We use this instance as the callback for connection and connection
            // failures.
            // Since no account name is passed, the user is prompted to choose.
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        // Connect the client. Once connected, the camera is launched.
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_CAPTURE_IMAGE:
                // Called after a photo has been taken.
                if (resultCode == Activity.RESULT_OK) {
                    // Store the image data as a bitmap for writing later.
                    mBitmapToSave = (Bitmap) data.getExtras().get("data");
                }
                break;
            case REQUEST_CODE_CREATOR:
                // Called after a file is saved to Drive.
                if (resultCode == RESULT_OK) {
                    Log.i(TAG, "Image successfully saved.");
                    mBitmapToSave = null;
                    // Just start the camera again for another photo.
                    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                            REQUEST_CODE_CAPTURE_IMAGE);
                }
                break;
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Called whenever the API client fails to connect.
        Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
        if (!result.hasResolution()) {
            // show the localized error dialog.
            GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
            return;
        }
        // The failure has a resolution. Resolve it.
        // Called typically when the app is not yet authorized, and an
        // authorization
        // dialog is displayed to the user.
        try {
            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (SendIntentException e) {
            Log.e(TAG, "Exception while starting resolution activity", e);
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "API client connected.");
        if (mBitmapToSave == null) {
            // This activity has no UI of its own. Just start the camera.
            startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                    REQUEST_CODE_CAPTURE_IMAGE);
            return;
        }
        saveFileToDrive();
    }

    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "GoogleApiClient connection suspended");
    }
}

In the code snippet, you can try to change the mimeType to application/vnd.google-apps.video and the Bitmap typecast to (lets say) byte[] . 在代码段中,您可以尝试将mimeType更改为application/vnd.google-apps.video ,并将Bitmap typecast更改为(可以说) byte[] I'm just not certain since this involves possibly large files and there's no documentation on the Android Drive API page about video uploads. 我不确定,因为这可能涉及大文件,并且Android Drive API页面上没有有关视频上传的文档。

There are other ways to approach this, though. 但是,还有其他方法可以解决此问题。 What I can suggest is for you to utilize the REST calls in uploading files . 我可以建议您在上传文件时利用REST调用。

For videos (which usually has a large file size), I'd suggest you use Resumable Uploads. 对于视频(通常文件较大),建议您使用可恢复上传。 It does have some prerequisites you'll need to do 它确实有一些先决条件,您需要做

The steps for using resumable upload include: 使用断点续传的步骤包括:

  1. Start a resumable session. 开始一个可恢复的会话。 Make an initial request to the upload URI that includes the metadata, if any. 向包含元数据(如果有)的上传URI发出初始请求。

  2. Save the resumable session URI. 保存可恢复的会话URI。 Save the session URI returned in the response of the initial request; 保存在初始请求的响应中返回的会话URI; you'll use it for the remaining requests in this session. 您将使用它处理此会话中的其余请求。

  3. Upload the file. 上载文件。 Send the media file to the resumable session URI. 将媒体文件发送到可恢复的会话URI。

More information can be found on the documentation. 可以在文档中找到更多信息。

Happy coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM