使用 Android 将文本文件上传到 Google 驱动器
Upload text file to Google Drive using Android
已编辑:我已将文本设置为如下字符串:
字符串文本 = ("Hello!");
我想将其转换为纯文本文件,然后上传到 Google 驱动器文件夹。我试过下面的代码,但它不完整,所以我不能说出现了什么错误。
我正在使用 Google Drive "Quick-start" 演示,并尝试根据我的需要对其进行定制。 Link: https://github.com/googledrive/android-quickstart
驱动类:
public class UploadDrive extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {
private static final String TAG = "androiddrivequickstart";
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;
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
//How to call? Can i use File from java.io?
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 textFile = new ByteArrayOutputStream();
//image.compress(Bitmap.CompressFormat.PNG, 100, textFile);
try {
outputStream.write(textFile.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("text/plain").setTitle("Log: test.txt").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");
}
}
如何调用另一个 class MainActivity 中的 finalResultText,以便将其转换为纯文本文件并上传到 Google Drive 文件夹?
假设您的问题是:'How do I upload a text file to Google Drive?',这里是快速概述:
1/ 在 developers console, see this 上获得您的应用授权。基本上,告诉 Google 您的由 SHA1 / 'package-name' 表示的应用程序需要访问 Drive API(不要忘记同意屏幕上的电子邮件地址)。此授权适用于 REST 和 GDAA api.
2/决定是否要使用REST or GDAA API to access the Drive. Each has (不过说来话长)。
3/ 看看 REST/GDAA wrapper demo here, it has the app authorization process in the MainActivity class (see onConnFail() method), and basic CRUD methods for both REST and GDAA 各自的 类。
祝你好运
更新
根据您在下面的评论,我假设您想要强制 QuickStart 演示为您工作。请记住,GDAA(或 REST)不关心内容是什么它只是一堆字节。因此,当 QuickStart 将位图转换为 PNG 并将其字节提供给输出流时,您必须使用字节串来完成。我很快将下面的 2 个基元拼凑在一起,它们将向 DriveContents 的输出流提供文件或字节数组(并且您可以将您拥有的任何内容转换为文件或字节 [])。
DriveContents file2Cont(DriveContents driveContents, java.io.File file) {
OutputStream oos = driveContents.getOutputStream();
if (oos != null) try {
InputStream is = new FileInputStream(file);
byte[] buf = new byte[8192];
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
} catch (Exception e) {/*handle errors*/}
finally {
try {
oos.close();
} catch (Exception ignore) { }
}
return driveContents;
}
DriveContents bytes2Cont(DriveContents driveContents, byte[] buf) {
OutputStream os = driveContents.getOutputStream();
try { os.write(buf);
} catch (IOException e) {/*handle errors*/}
finally {
try { os.close();
} catch (Exception e) {/*handle errors*/}
}
return driveContents;
}
已编辑:我已将文本设置为如下字符串:
字符串文本 = ("Hello!");
我想将其转换为纯文本文件,然后上传到 Google 驱动器文件夹。我试过下面的代码,但它不完整,所以我不能说出现了什么错误。
我正在使用 Google Drive "Quick-start" 演示,并尝试根据我的需要对其进行定制。 Link: https://github.com/googledrive/android-quickstart
驱动类:
public class UploadDrive extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {
private static final String TAG = "androiddrivequickstart";
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;
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
//How to call? Can i use File from java.io?
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 textFile = new ByteArrayOutputStream();
//image.compress(Bitmap.CompressFormat.PNG, 100, textFile);
try {
outputStream.write(textFile.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("text/plain").setTitle("Log: test.txt").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");
}
}
如何调用另一个 class MainActivity 中的 finalResultText,以便将其转换为纯文本文件并上传到 Google Drive 文件夹?
假设您的问题是:'How do I upload a text file to Google Drive?',这里是快速概述:
1/ 在 developers console, see this 上获得您的应用授权。基本上,告诉 Google 您的由 SHA1 / 'package-name' 表示的应用程序需要访问 Drive API(不要忘记同意屏幕上的电子邮件地址)。此授权适用于 REST 和 GDAA api.
2/决定是否要使用REST or GDAA API to access the Drive. Each has
3/ 看看 REST/GDAA wrapper demo here, it has the app authorization process in the MainActivity class (see onConnFail() method), and basic CRUD methods for both REST and GDAA 各自的 类。
祝你好运
更新
根据您在下面的评论,我假设您想要强制 QuickStart 演示为您工作。请记住,GDAA(或 REST)不关心内容是什么它只是一堆字节。因此,当 QuickStart 将位图转换为 PNG 并将其字节提供给输出流时,您必须使用字节串来完成。我很快将下面的 2 个基元拼凑在一起,它们将向 DriveContents 的输出流提供文件或字节数组(并且您可以将您拥有的任何内容转换为文件或字节 [])。
DriveContents file2Cont(DriveContents driveContents, java.io.File file) {
OutputStream oos = driveContents.getOutputStream();
if (oos != null) try {
InputStream is = new FileInputStream(file);
byte[] buf = new byte[8192];
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
} catch (Exception e) {/*handle errors*/}
finally {
try {
oos.close();
} catch (Exception ignore) { }
}
return driveContents;
}
DriveContents bytes2Cont(DriveContents driveContents, byte[] buf) {
OutputStream os = driveContents.getOutputStream();
try { os.write(buf);
} catch (IOException e) {/*handle errors*/}
finally {
try { os.close();
} catch (Exception e) {/*handle errors*/}
}
return driveContents;
}