Android更新Google云端硬盘上已创建文件的文件内容

时间:2015-02-20 06:10:16

标签: java android google-drive-android-api

我已经完成了Google驱动器集成,并且在集成中我创建了一个文件并在文件上写了一些文本并将其保存到登录用户的驱动器中它运行正常但我想更新内容文件我已经创建了一个保存到驱动器,我已经做了大量的研究,但无法找到演示或任何代码,请任何人指导我,我将发布我的代码,我正在创建文件并保存到我的驱动器

 public class MainActivity extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    Button b ,editfile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        b = (Button) findViewById(R.id.createfile);
        editfile = (Button) findViewById(R.id.editfile);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub


                // create new contents resource
                /**
                 * A code to illustrate how to create a new FILE in the Drive.
                 */
                Drive.DriveApi.newContents(getGoogleApiClient())
                        .setResultCallback(contentsCallback);

            }
        });



    }


    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

     /**
     * Called when activity gets visible. A connection to Drive services need to
     * be initiated as soon as the activity is visible. Registers
     * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
     * activities itself.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    //.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();
    }
    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, 1);
            } catch (IntentSender.SendIntentException e) {
                // Unable to resolve, message user appropriately
            }
        } else {
            GooglePlayServicesUtil.getErrorDialog(
                    connectionResult.getErrorCode(), this, 0).show();
        }
    }

    @Override
    protected void onActivityResult(final int requestCode,
            final int resultCode, final Intent data) {
        switch (requestCode) {
        case 1:
            if (resultCode == RESULT_OK) {
                mGoogleApiClient.connect();
            }
            break;
        }
    }

    public GoogleApiClient getGoogleApiClient() {
        return mGoogleApiClient;
    }





    /**
     * A code to illustrate how to create a new FILE with some text on the file in the Google Drive.
     */
    final private ResultCallback<ContentsResult> contentsCallback = new ResultCallback<ContentsResult>() {
        @Override
        public void onResult(ContentsResult result) {
            if (!result.getStatus().isSuccess()) {
                Toast.makeText(MainActivity.this,"Error while trying to create new file contents" ,Toast.LENGTH_LONG).show();
                return;
            }

            Contents driveContents = result.getContents();
            // write content to DriveContents
            OutputStream outputStream = driveContents.getOutputStream();
            Writer writer = new OutputStreamWriter(outputStream);
            try {
                writer.write(information_data());
                writer.close();
            } catch (IOException e) {
                Log.e("IOExceptions=", e.toString());
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle("testFile.txt")
                    .setMimeType("text/plain")
                    .setStarred(true)
                    .build();
            // create a file on root folder
            Drive.DriveApi.getRootFolder(getGoogleApiClient())
                    .createFile(getGoogleApiClient(), changeSet, result.getContents())
                    .setResultCallback(fileCallback);
        }
    };

    final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
        @Override
        public void onResult(DriveFileResult result) {
            if (!result.getStatus().isSuccess()) {
                Toast.makeText(MainActivity.this,"Error while trying to create the file" ,Toast.LENGTH_LONG).show();

                return;
            }
            Toast.makeText(MainActivity.this,"Created a file: " + result.getDriveFile().getDriveId(),Toast.LENGTH_LONG).show();
            Log.e("result.getDriveFile().getDriveId=", ""+result.getDriveFile().getDriveId());
            Log.e("result.getStatus()=", ""+result.getStatus().toString());

            //Opening the file contents Reading files
            driveOpnefileContents(result.getDriveFile());

        }
    };

    public  void driveOpnefileContents(DriveFile driveFile) {
        // TODO Auto-generated method stub
        Log.e("driveOpnefileContents=", "driveOpnefileContents");
        driveFile.openContents(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, new DownloadProgressListener() {

            @Override
            public void onProgress(long bytesDownloaded, long bytesExpected) {
                 // Update progress dialog with the latest progress.
                Log.e("onProgress=", "onProgress");
                int progress = (int)(bytesDownloaded*100/bytesExpected);
                Log.e("progress", String.format("Loading progress: %d percent=", progress));
            }
        })
        .setResultCallback(contentsOpenedCallback);

    }

    ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
        @Override
        public void onResult(ContentsResult result) {
            if (!result.getStatus().isSuccess()) {
                // display an error saying file can't be opened
                 Toast.makeText(MainActivity.this,"display an error saying file can't be opened" ,Toast.LENGTH_LONG).show();
                return;
            }
            // DriveContents object contains pointers
            // to the actual byte stream
            try {
                Contents driveContents = result.getContents();
                BufferedReader reader = new BufferedReader(new InputStreamReader(driveContents.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                String contentsAsString = builder.toString();
                Log.e("Reading File Contents As String=", ""+contentsAsString);
                driveContents.close();
                /*try {
                    ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
                    FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
                    // Read to the end of the file.
                    fileInputStream.read(new byte[fileInputStream.available()]);

                    // Append to the file.
                    FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
                    Writer writer = new OutputStreamWriter(fileOutputStream);
                    writer.write("editing the contents of the saved file");
                    writer.close();

                    driveContents.close();

                } catch (IOException e) {
                    Log.e("IOExceptionAppend to the file.=", e.toString());
                    //java.io.IOException: write failed: EBADF (Bad file number)
                }*/
                Log.e("Append to the file.=", "Append to the file.");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.e("IOExceptionAppend to the file2.=", e.toString());
            }

        }
    };

    public String information_data(){
        String result = "";
        try {
            JSONObject jArrayFacebookData = new JSONObject();
            JSONObject jObjectType = new JSONObject();
            // put elements into the object as a key-value pair
            jObjectType.put("info", "facebook_login");
            jArrayFacebookData.put("Result", jObjectType);
            // 2nd array for user information
            JSONObject jObjectData = new JSONObject();
            // Create Json Object using Facebook Data
            jObjectData.put("facebook_user_id", "facebook_user_id");
            jObjectData.put("first_name", "achin");
            jObjectData.put("last_name", "verma");
            jObjectData.put("email", "xvz");
            jObjectData.put("username", "achin");
            jObjectData.put("birthday", "28 april 90");
            jObjectData.put("gender", "male");
            jObjectData.put("location", "mohali");
            jObjectData.put("display_photo", "link");
            jArrayFacebookData.put("data", jObjectData);
            //Log.e("jArrayFacebookData=", ""+jArrayFacebookData);
            result = ""+jArrayFacebookData;
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return result;

    }

}

2 个答案:

答案 0 :(得分:1)

以下是代码段&#39;更新&#39;做你需要的(我想)。它正在使用&#39; await&#39;调用必须运行UI线程的版本,或者您可以将其转换为回调版本。您实际上只需要以

开头的部分
  

dFile.open(mGAC,DriveFile.MODE_WRITE_ONLY,null)

(将DriveId变为DriveFile后)并确保致电&#39; commit&#39;在它上面

  /**
   * update file in GOODrive
   * @param dId   file  id
   * @param titl  new file name (optional)
   * @param mime  new file mime type (optional, null or MIME_FLDR indicates folder)
   * @param buf   new file contents (optional)
   * @return       success status
   */
  static boolean update(DriveId dId, String titl, String mime, String desc, byte[] buf){
    if (dId == null || !isConnected())  return false;   //------------>>>

    Boolean bOK = false;
    Builder mdBd = new MetadataChangeSet.Builder();
    if (titl != null) mdBd.setTitle(titl);
    if (mime != null) mdBd.setMimeType(mime);
    if (desc != null) mdBd.setDescription(desc);
    MetadataChangeSet meta = mdBd.build();

    if (mime == null || UT.MIME_FLDR.equals(mime)) {
      DriveFolder dFldr = Drive.DriveApi.getFolder(mGAC, dId);
      MetadataResult r1 = dFldr.updateMetadata(mGAC, meta).await();
      bOK = (r1 != null) && r1.getStatus().isSuccess();

    } else {
      DriveFile dFile = Drive.DriveApi.getFile(mGAC, dId);
      MetadataResult r1 = dFile.updateMetadata(mGAC, meta).await();
      if ((r1 != null) && r1.getStatus().isSuccess() && buf != null) {
        DriveContentsResult r2 = dFile.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
        if (r2.getStatus().isSuccess()) {
          Status r3 = bytes2Cont(r2.getDriveContents(), buf).commit(mGAC, meta).await();
          bOK = (r3 != null && r3.isSuccess());
        }
      }
    }
    return bOK;
  }

在您的情况下不需要更新元数据,因此您可以修改代码或只传递空值。您的新内容必须作为字节缓冲区传递(字符串转为字节,jpeg数据缓冲区,...)。

此方法的上下文can be found here。祝你好运

答案 1 :(得分:0)

我知道,这个答案来晚了,但是Google总是更新他的api,因此我愿意添加答案。 这是kotlin代码,目前可以使用

fun updateDriveFile(fileCache: File, googleRecentFileModel: GoogleRecentFileModel): Deferred<Boolean> = CoroutineScope(Dispatchers.Default).async {
        var result = false
        val drive = DriveId.decodeFromString(googleRecentFileModel.stringDriveId).asDriveFile()
        val openFileTask = driveResourceClient?.openFile(drive, DriveFile.MODE_WRITE_ONLY)
        openFileTask?.continueWithTask { task ->
            val contents = task.result
            contents!!.outputStream.use {
                val fileBytes = ByteArray(fileCache.length().toInt())
                val fileIS = FileInputStream(fileCache)
                fileIS.read(fileBytes)
                fileIS.close()
                it.write(fileBytes)
                it.flush()
                it.close()
                result = true
            }
            driveResourceClient?.commitContents(contents, null)
        }

        result
    }