簡體   English   中英

使用Android將文本文件上傳到Google雲端硬盤

[英]Upload text file to Google Drive using Android

編輯:我已將文本設置為如下字符串:

String text =(“Hello!”);

我想將其轉換為純文本文件,然后上傳到Google雲端硬盤文件夾。 我試過下面的代碼,但它沒有完整,所以我不能說出現了什么錯誤。

我正在使用谷歌硬盤“快速啟動”演示,並嘗試根據我的需要定制它。 鏈接: https//github.com/googledrive/android-quickstart

DriverClass:

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");
}
 }

如何調用另一個名為MainActivity的類中的finalResultText,以便將其轉換為純文本文件以上傳到Google Drive文件夾?

假設您提出的問題是:“如何將文本文件上傳到Google雲端硬盤?”,以下是快速概述:

1 /在開發者控制台上授權您的應用,請參閱此內容 基本上,告訴Google您的SHA1 /'package-name'代表的應用需要訪問Drive API(請勿在同意屏幕上忘記您的電子郵件地址)。 此授權適用於REST和GDAA API。

2 /決定是否要使用RESTGDAA API訪問雲端硬盤。 每個都有優點/缺點 (但這是一個很長的故事)。

3 /在這里看一下REST / GDAA包裝器演示 ,它在MainActivity類中有應用程序授權過程(參見onConnFail()方法),以及各自類中RESTGDAA的基本CRUD方法。

祝好運

UPDATE
根據您在下面的評論,我假設您想強制QuickStart演示適合您。 請記住,GDAA(或REST)不關心內容是什么它只是一堆字節。 因此,當QuickStart將Bitmap轉換為PNG並將輸出流與其字節一起提供時,您必須使用一堆字節來完成。 我快速將下面的兩個原語拼湊在一起,這將為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;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM