[英]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 API
和Drive 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 .
它的范围更广,可以处理GDAA和REST API以及Google帐户选择流程 。 If you use Android Studio, you should be able to make use of it.
如果您使用的是Android Studio,则应该可以使用它。 Just a few points:
请注意以下几点:
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}”。
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.