使用以下代码(取自android-quickstart),如果您拍摄多张照片,此代码可以生成多个具有相同名称的文件.如何修改以确保替换具有相同名称的文件?
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.newContents(mGoogleapiclient).setResultCallback(new ResultCallback<ContentsResult>() { @OverrIDe public voID onResult(ContentsResult 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.getContents().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) .setinitialContents(result.getContents()) .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 public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGoogleapiclient = new Googleapiclient.Builder(this) .addAPI(Drive.API) .addScope(Drive.ScopE_file) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @OverrIDe protected voID onStart() { super.onStart(); 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"); }}
解决方法:
我按如下方式打开驱动文件进行写入:
writeDrivefile(Drivefile file, Handler handler){ //see query task below to get a drive file by its name. Be careful you can get multiple data elements in the MetadataBuffer below if you have uploaded multiple files with the same name. Task<DriveContents> openfileTask = myDriveResourceClIEnt.openfile(file, Drivefile.MODE_WRITE_ONLY);
然后用该任务将一些对象字节写入流someObject.getBytes(),这里没有魔法.然后提交结果.
openfileTask .continueWithTask(task -> { DriveContents contents = task.getResult(); // Process contents... try (OutputStream writer = contents.getoutputStream()) { writer.write(someObject.getBytes()); writer.close(); } //Add whatever Metadata you want here MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setLastVIEwedByMeDate(new Date()) .build(); //commit the file to Google Drive Task<VoID> commitTask = myDriveResourceClIEnt.commitContents(contents, changeSet); handler.onWriteResults(); return commitTask; }) .addOnFailureListener(e -> { // Handle failure Log.e(TAG, "Unable to read contents", e); handler.onDriveError(e); });
处理程序只是我为Drive API执行后要处理的错误或结果定义的接口.您还可以添加addOnCompleteListener()以在写入完成后处理某些内容.
file是Drivefile的一个实例,可以通过查询任务获取.在任务代码块中找到的元数据有一个getDriveID()方法,它有一个asDriveffile()方法来获取上面需要的Drive文件.
query query = new query.Builder() .addFilter(Filters.eq(SearchableFIEld.Title, "file name")) .build();Task<MetadataBuffer> queryTask = mDriveResourceClIEnt.query(query);
然后处理MetadataBuffer
queryTask.continueWithTask( task -> { MetadataBuffer MetadataBuffer = task.getResult() ; //I have this loop because I wanted to kNow if there were other versions of the file on the drive for(Metadata data : MetadataBuffer) { Log.d(TAG, "******************* MetadataBuffer Title is " + data.getTitle()); if(data.getTitle().equals("file name")){ //this is just a method I defined that encapsulates the drive writing code above. writeDrivefile(data.getDriveID().asDrivefile(), JsonContent, handler); } } return task; }) .addOnCompleteListener(task -> { //some complete tasks } }) .addOnFailureListener(e -> { Log.e(TAG, "************************** Error searching for " + filename, e); handler.onDriveError(e); });
此代码全部用于写入App文件夹,但您只需在创建资源客户端时设置正确的范围.
删除驱动器文件可以按如下方式完成.
public voID deleteDrivefile(DriveResource file){ Task<VoID> deleteTask = mDriveResourceClIEnt.delete(file); deleteTask .continueWith(task -> { Log.d(TAG, "************* Deleted drive file: " + file.getDriveID().toInvariantString()); return task; }) .addOnFailureListener(e -> { //log some sort of error for yourself });}
总结 以上是内存溢出为你收集整理的android – 如何在Google云端硬盘中替换文件?全部内容,希望文章能够帮你解决android – 如何在Google云端硬盘中替换文件?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)