简体   繁体   English

通过Android访问Google云端硬盘

[英]Accessing Google Drive through Android

I am trying to access the google drive through android app. 我正在尝试通过Android应用访问Google驱动器。 I have turned on the Drive API and Drive SDK in Google Developer Console and generated a OAuth Client id. 我已经在Google Developer Console中打开了Drive APIDrive SDK ,并生成了一个OAuth客户端ID。

Inserted the Client key in AndroidManifest.xml as AndroidManifest.xml中将客户端密钥插入为

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

And a permission as 和许可为

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

This is the code which I am trying to run (Originally from 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");
}
}

This is the error I am getting 这是我得到的错误

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}`

Am I making any errors above? 我在上面犯任何错误吗? Are there any better simple example to access Google Drive from Android? 有没有更好的简单示例可以从Android访问Google云端硬盘?

The Quick Start you play with as as simple as it gets, to answer you question. 您可以轻松使用快速入门来回答您的问题。

But it may be outdated (I don't know, last time I ran it was 8 months ago). 但是它可能已经过时了(我不知道,我上一次运行它是在8个月前)。 GooPlayServices are on the 6.5.+ version and last update of that code was half a year ago. GooPlayServices的版本为6.5。+,该代码的最新更新是半年前。 I have some code on GitHub that I can't claim is simpler, but (probably) more in line with current lib version. 在GitHub上有一些代码 ,我不能声称它更简单,但是(可能)更符合当前的lib版本。 It is a bit broader and deals with both GDAA and REST APIs, as well as with the Google account pick process . 它的范围更广,可以处理GDAAREST API以及Google帐户选择流程 If you use Android Studio, you should be able to make use of it. 如果您使用的是Android Studio,则应该可以使用它。 Just a few points: 请注意以下几点:

  • You have go through the Developers Console stuff . 您已经浏览了Developers Console的内容 Basically you must have your 'package name' / SHA1 registered. 基本上,您必须注册“包装名称” / SHA1。 I usually register both debug and release SHA1s and double check if my APKs are actually correct - see SO 28532206 我通常会同时注册调试和发布SHA1,并仔细检查我的APK是否正确-请参见SO 28532206
  • Look at SO 28439129 here to get some sense what is involved in connecting to GooDrive 请看SO 28439129,以了解连接GooDrive涉及的内容
  • If you use the code I mentioned, make sure you environment is in line with dependencies in 'build.gradle' there (my SDK Manager shows GooPlaySvcs 21, which is 'com.google.android.gms:play-services:6.5.87') 如果您使用我提到的代码,请确保您的环境与那里的“ build.gradle”中的依赖项保持一致(我的SDK管理器显示的是GooPlaySvcs 21,即“ com.google.android.gms:play-services:6.5.87” “)

Good Luck 祝好运

This error "GoogleApiClient connection failed: ConnectionResult{statusCode=INTERNAL_ERROR, resolution=null} " occurs if you have not created credentials for your application. 如果您尚未为应用程序创建凭据,则会发生此错误“ GoogleApiClient连接失败:ConnectionResult {statusCode = INTERNAL_ERROR,resolution = null}”。

  • Go to console- https://console.cloud.google.com/apis/credentials 转到控制台-https : //console.cloud.google.com/apis/credentials
  • Click on Create Credentials 单击创建凭据
  • Select QAuth client ID 选择QAuth客户端ID
  • Select Application type as Android if you are running from AndroidStudio 如果您是从AndroidStudio运行,则将应用程序类型选择为Android
  • Add the projectname, SHA key & package name 添加项目名称,SHA密钥和程序包名称
  • Run the project and the application should work. 运行项目,该应用程序应该可以工作。

I faced issue running android-quickstart-master and the issue got resolved after following the above steps 在执行上述步骤后,我遇到了运行android-quickstart-master的问题,此问题已得到解决

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

相关问题 在Android中访问Google驱动器 - Accessing google drive in android 从Android访问Google驱动器 - Accessing google drive from Android Google Drive是否通过代码与Android集成? - Does Google Drive integrate with Android through code? 使用通过代码提供的用户名和密码访问Google Drive - Accessing google drive with user name and password provided through code 无需身份验证即可从 Android 应用访问公共 Google Drive 文件夹 - Accessing public Google Drive folder from Android app without authenticating 像服务器一样访问Google云端硬盘? - Accessing Google Drive like server? 通过Google云端硬盘基于PC和MAC的Android Studio多平台开发 - Android Studio Multiplatform Development baseon PC and MAC through Google Drive 在android中通过意图浏览文件时排除谷歌驱动器选项 - exclude the google drive option in browsing files through intent in android 适用于Java或Google云端硬盘的Google API客户端库,用于从Android访问Google日历/任务 - Google APIs Client Library for Java or Google Drive for accessing Google calendar / tasks from Android Google Drive Android API-是否可以通过链接打开Drive文件? - Google Drive Android API - Is there any way to open a Drive file through a link?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM