【问题标题】:Accessing Google Drive through Android通过 Android 访问 Google Drive
【发布时间】:2017-03-19 23:12:50
【问题描述】:

我正在尝试通过 android 应用程序访问 google 驱动器。我在 Google Developer Console 中打开了 Drive APIDrive SDK 并生成了一个 OAuth 客户端 ID。

AndroidManifest.xml 中插入客户端密钥

<meta-data
  android:name="com.google.android.apps.drive.APP_ID"
  android:value=id="***CLIENT_KEY***" />

还有一个权限

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.INTERNET"/> 

这是我正在尝试运行的代码(最初来自here

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.MetadataChangeSet;

/**
 * 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 MainActivity extends Activity implements ConnectionCallbacks,
    OnConnectionFailedListener {

private static final String TAG = "android-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.
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 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");
}
}

这是我遇到的错误

02-19 18:58:18.204  27221-27221/com.gajendraprofile.drive I/android-drive-quickstart﹕ GoogleApiClient connection failed: ConnectionResult{statusCode=INTERNAL_ERROR, resolution=null}
02-19 18:58:47.584  27431-27431/com.gajendraprofile.drive I/android-drive-quickstart﹕ GoogleApiClient connection failed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{21b27910: android.os.BinderProxy@21b00a7c}}
02-19 18:58:51.564  27431-27431/com.gajendraprofile.drive I/android-drive-quickstart﹕ GoogleApiClient connection failed: ConnectionResult{statusCode=INTERNAL_ERROR, resolution=null}`

我是否在上面犯了任何错误?有没有更好的简单示例从 Android 访问 Google Drive?

【问题讨论】:

  • "Inserted the Client key in AndroidManifest.xml as..." 来自哪里?我从未听说过或使用过类似的东西。
  • 感谢您的回复,我看到在最后一条评论中添加了来自here 的清单密钥。我搜索了很多网站和论坛。我无法找到应如何将客户端 ID 密钥分配或链接到应用程序。我是否需要像 Google Maps Api Key 一样在清单中分配 api 密钥。或者我只需要在谷歌控制台中用我的包名生成密钥,当从应用程序发送请求时它会自动获取?。
  • 顺便说一句,为了运行任何演示,我只需要 DriveAPI(而不是 DriveSDK)。但这可能无关紧要
  • 我查看了您在上面评论中提到的链接。 GDAA 于 2014 年 1 月出台,去年发生了几次变化。大约在 2014 年 3 月之前,没有任何问题/答案具有很大的相关性。

标签: android google-drive-api google-drive-android-api


【解决方案1】:

您使用的Quick Start 尽可能简单地回答您的问题。

但它可能已经过时(我不知道,我上次运行它是 8 个月前)。 GooPlayServices 在 6.5.+ 版本上,该代码的最后一次更新是半年前。我有一些 code on GitHub 不能说更简单,但(可能)更符合当前的 lib 版本。它的范围更广一些,可以处理GDAAREST API,以及Google 帐户选择流程。如果你使用 Android Studio,你应该可以使用它。 只是几点:

  • 您已通过Developers Console stuff。基本上你必须注册你的“包名”/SHA1。我通常会同时注册调试和发布 SHA1,并仔细检查我的 APK 是否真的正确 - 请参阅 SO 28532206
  • 查看SO 28439129 here 以了解连接到 GooDrive 所涉及的内容
  • 如果您使用我提到的代码,请确保您的环境符合 'build.gradle' 中的依赖项(我的 SDK 管理器显示 GooPlaySvcs 21,即 'com.google.android.gms:play-services: 6.5.87')

祝你好运

【讨论】:

    【解决方案2】:

    如果您尚未为应用程序创建凭据,则会出现此错误“GoogleApiClient connection failed: ConnectionResult{statusCode=INTERNAL_ERROR, resolution=null}”。

    • 转到控制台-https://console.cloud.google.com/apis/credentials
    • 点击创建凭据
    • 选择 QAuth 客户端 ID
    • 如果您从 AndroidStudio 运行,请选择应用程序类型为 Android
    • 添加项目名称、SHA 密钥和包名称
    • 运行项目,应用程序应该可以运行。

    我在运行 android-quickstart-master 时遇到了问题,按照上述步骤后问题得到了解决

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-17
      • 2013-02-26
      • 2018-11-10
      • 2021-08-09
      • 2020-02-26
      • 1970-01-01
      • 2020-07-14
      • 2017-08-31
      相关资源
      最近更新 更多