Java 使用Android将文本文件上载到Google Drive

Java 使用Android将文本文件上载到Google Drive,java,android,google-drive-api,google-drive-android-api,Java,Android,Google Drive Api,Google Drive Android Api,已编辑:我已将文本设置为如下字符串: 字符串文本=(“你好!”) 我想把它变成一个纯文本文件,然后上传到谷歌驱动器文件夹。我试过下面的代码,但它不完整,所以我不能说出现了什么错误 我正在使用GoogleDrive的“快速入门”演示,并试图根据我的需要进行定制。链接: 驾驶员等级: public class UploadDrive extends Activity implements ConnectionCallbacks,OnConnectionFailedListener { priva

已编辑:我已将文本设置为如下字符串:

字符串文本=(“你好!”)

我想把它变成一个纯文本文件,然后上传到谷歌驱动器文件夹。我试过下面的代码,但它不完整,所以我不能说出现了什么错误

我正在使用GoogleDrive的“快速入门”演示,并试图根据我的需要进行定制。链接:

驾驶员等级:

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");
}
 }
公共类UploadDrive extends活动实现ConnectionCallbacks、OnConnectionFailedListener{
私有静态最终字符串标记=“androiddrivequickstart”;
私有静态最终整数请求\代码\捕获\图像=1;
私有静态最终整数请求\代码\创建者=2;
私有静态最终整数请求\代码\分辨率=3;
私人GoogleapClient MGoogleapClient;
私有位图mbitmatosave;
私有void saveFileToDrive(){
//首先创建一个新的内容,并设置一个回调。
Log.i(标记“创建新内容”);
//如何调用?我可以使用java.io中的文件吗?
最终位图图像=mBitmapToSave;
Drive.DriveApi.newDriveContents(mGoogleApiClient.setResultCallback(newResultCallback()){
@凌驾
public void onResult(DriveContentsResult结果){
//如果手术不成功,我们什么也做不了
//而且必须
//失败。
如果(!result.getStatus().issucess()){
Log.i(标记“未能创建新内容”);
返回;
}
//否则,我们可以将数据写入新内容。
Log.i(标记“创建的新内容”);
//获取内容的输出流。
OutputStream OutputStream=result.getDriveContents().getOutputStream();
//从中写入位图数据。
ByteArrayOutputStream textFile=新建ByteArrayOutputStream();
//image.compress(Bitmap.CompressFormat.PNG,100,textFile);
试一试{
write(textFile.toByteArray());
}捕获(IOE1异常){
Log.i(标记“无法写入文件内容”);
}
//创建初始元数据-MIME类型和标题。
//请注意,用户稍后可以更改标题。
MetadataChangeSet MetadataChangeSet=新建MetadataChangeSet.Builder()
.setMimeType(“text/plain”).setTitle(“Log:test.txt”).build();
//为文件选择器创建意图,并启动它。
IntentSender IntentSender=Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(结果.getDriveContents())
.构建(mGoogleApiClient);
试一试{
startinentsenderforresult(
intentSender,请求\代码\创建者,null,0,0,0);
}捕获(发送){
Log.i(标记“未能启动文件选择器”);
}
}
});
}
@凌驾
受保护的void onResume(){
super.onResume();
if(mGoogleApiClient==null){
//创建API客户端并将其绑定到实例变量。
//我们使用这个实例作为连接和连接的回调
//失败。
//由于未传递任何帐户名,因此会提示用户选择。
mgoogleapclient=新的Googleapclient.Builder(此)
.addApi(Drive.API)
.addScope(驱动器.SCOPE\u文件)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
}
//连接客户端。一旦连接,相机将启动。
mGoogleApiClient.connect();
}
@凌驾
受保护的void onPause(){
if(mGoogleApiClient!=null){
mGoogleApiClient.disconnect();
}
super.onPause();
}
@凌驾
受保护的void onActivityResult(最终int请求代码、最终int结果代码、最终意图数据){
开关(请求代码){
案例请求\代码\捕获\图像:
//拍完照片后打电话来。
if(resultCode==Activity.RESULT\u确定){
//将图像数据存储为位图,以便以后写入。
MbitMatoSave=(位图)data.getExtras().get(“数据”);
}
打破
案例请求\代码\创建者:
//将文件保存到驱动器后调用。
if(resultCode==RESULT\u OK){
Log.i(标记“图像已成功保存”);
mbitmatosave=null;
//只需再次启动相机,拍摄另一张照片。
startActivityForResult(新意图(MediaStore.ACTION\u IMAGE\u CAPTURE)、请求\u CODE\u CAPTURE\u IMAGE);
}
打破
}
}
@凌驾
连接失败的公共void(连接结果){
//每当API客户端连接失败时调用。
Log.i(标记“GoogleAppClient连接失败:”+result.toString());
如果(!result.hasResolution()){
//显示本地化错误对话框。
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),this,0.show();
返回;
}
//失败有解决的办法。解决它。
//通常在应用程序尚未授权时调用,并且
//授权书
//对话框将显示给用户。
试一试{
result.startResolutionForResult(这是请求代码解析);
}捕获(发送){
Log.e(标记“启动解析活动时异常”,e);
}
}
@凌驾
未连接的公共无效(捆绑连接提示){
Log.i(标记“API客户端已连接”);
if(mbitmatosave==null){
//此活动没有自己的UI。只需启动相机。
startActivityForResult(新意图(MediaStore.ACTION\u IMAGE\u CAPTURE),
请求(编码)(捕获)(图像);;
返回;
}
saveFileToDrive();
}
@凌驾
聚氨基甲酸酯
 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;
  }