com.google.android.gms.drive.DriveContents Java Examples
The following examples show how to use
com.google.android.gms.drive.DriveContents.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleDriveClient.java From financisto with GNU General Public License v2.0 | 6 votes |
@Subscribe(threadMode = ThreadMode.BACKGROUND) public void doRestore(DoDriveRestore event) { try { ConnectionResult connectionResult = connect(); if (connectionResult.isSuccess()) { DriveFile file = Drive.DriveApi.getFile(googleApiClient, event.selectedDriveFile.driveId); DriveApi.DriveContentsResult contentsResult = file.open(googleApiClient, DriveFile.MODE_READ_ONLY, null).await(); if (contentsResult.getStatus().isSuccess()) { DriveContents contents = contentsResult.getDriveContents(); try { DatabaseImport.createFromGoogleDriveBackup(context, db, contents).importDatabase(); bus.post(new DriveRestoreSuccess()); } finally { contents.discard(googleApiClient); } } else { handleFailure(contentsResult.getStatus()); } } else { handleConnectionResult(connectionResult); } } catch (Exception e) { handleError(e); } }
Example #2
Source File: GoogleDriveClient.java From financisto with GNU General Public License v2.0 | 6 votes |
private Status createFile(DriveFolder folder, String fileName, byte[] bytes) throws IOException { MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle(fileName) .setMimeType(Export.BACKUP_MIME_TYPE).build(); // Create a file in the root folder DriveApi.DriveContentsResult contentsResult = Drive.DriveApi.newDriveContents(googleApiClient).await(); Status contentsResultStatus = contentsResult.getStatus(); if (contentsResultStatus.isSuccess()) { DriveContents contents = contentsResult.getDriveContents(); contents.getOutputStream().write(bytes); DriveFolder.DriveFileResult fileResult = folder.createFile(googleApiClient, changeSet, contents).await(); return fileResult.getStatus(); } else { return contentsResultStatus; } }
Example #3
Source File: EditContentsAsyncTask.java From ToDay with MIT License | 6 votes |
@Override protected Boolean doInBackgroundConnected(EditContentParams... args) { DriveFile file = args[0].getFileToWrite(); String dataToWrite = args[0].getDataToWrite(); try { DriveApi.DriveContentsResult driveContentsResult = file.open( getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await(); if (!driveContentsResult.getStatus().isSuccess()) { return false; } DriveContents driveContents = driveContentsResult.getDriveContents(); OutputStream outputStream = driveContents.getOutputStream(); outputStream.write(dataToWrite.getBytes()); com.google.android.gms.common.api.Status status = driveContents.commit(getGoogleApiClient(), null).await(); return status.getStatus().isSuccess(); } catch (IOException e) { AppUtils.showMessage(context,"Failed to write data to file."); } return false; }
Example #4
Source File: MainActivity.java From drive-android-quickstart with Apache License 2.0 | 6 votes |
/** 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; mDriveResourceClient .createContents() .continueWithTask( new Continuation<DriveContents, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<DriveContents> task) throws Exception { return createFileIntentSender(task.getResult(), image); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Failed to create new contents.", e); } }); }
Example #5
Source File: CreateFileInFolderActivity.java From android-samples with Apache License 2.0 | 6 votes |
private void createFileInFolder(final DriveFolder parent) { getDriveResourceClient() .createContents() .continueWithTask(task -> { DriveContents contents = task.getResult(); OutputStream outputStream = contents.getOutputStream(); try (Writer writer = new OutputStreamWriter(outputStream)) { writer.write("Hello World!"); } MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle("New file") .setMimeType("text/plain") .setStarred(true) .build(); return getDriveResourceClient().createFile(parent, changeSet, contents); }) .addOnSuccessListener(this, driveFile -> showMessage(getString(R.string.file_created, driveFile.getDriveId().encodeToString()))) .addOnFailureListener(this, e -> { Log.e(TAG, "Unable to create file", e); showMessage(getString(R.string.file_create_error)); }); }
Example #6
Source File: MainActivity.java From android-samples with Apache License 2.0 | 5 votes |
private Task<Void> saveFile() { Log.d(TAG, "Saving file."); // [START drive_android_reopen_for_write] Task<DriveContents> reopenTask = getDriveResourceClient().reopenContentsForWrite(mDriveContents); // [END drive_android_reopen_for_write] return reopenTask .continueWithTask(task -> { // [START drive_android_write_conflict_strategy] DriveContents driveContents = task.getResult(); OutputStream outputStream = driveContents.getOutputStream(); try (Writer writer = new OutputStreamWriter(outputStream)) { writer.write(mEditText.getText().toString()); } // ExecutionOptions define the conflict strategy to be used. // [START drive_android_execution_options] ExecutionOptions executionOptions = new ExecutionOptions.Builder() .setNotifyOnCompletion(true) .setConflictStrategy( ExecutionOptions.CONFLICT_STRATEGY_KEEP_REMOTE) .build(); return getDriveResourceClient().commitContents( driveContents, null, executionOptions); // [END drive_android_execution_options] // [END drive_android_write_conflict_strategy] }) .continueWithTask(task -> { showMessage(getString(R.string.file_saved)); Log.d(TAG, "Reopening file for read."); return loadContents(mGroceryListFile); }); }
Example #7
Source File: MainActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Gets the grocery list items. */ private Task<Void> loadContents(DriveFile file) { mGroceryListFile = file; Task<DriveContents> loadTask = getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY); return loadTask.continueWith(task -> { Log.d(TAG, "Reading file contents."); mDriveContents = task.getResult(); InputStream inputStream = mDriveContents.getInputStream(); String groceryListStr = ConflictUtil.getStringFromInputStream(inputStream); mEditText.setText(groceryListStr); return null; }); }
Example #8
Source File: MainActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Creates an {@link IntentSender} to start a dialog activity with configured {@link * CreateFileActivityOptions} for user to create a new photo in Drive. */ private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image) { Log.i(TAG, "New contents created."); // Get an output stream for the contents. OutputStream outputStream = driveContents.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 e) { Log.w(TAG, "Unable to write file contents.", e); } // 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(); // Set up options to configure and display the create file activity. CreateFileActivityOptions createFileActivityOptions = new CreateFileActivityOptions.Builder() .setInitialMetadata(metadataChangeSet) .setInitialDriveContents(driveContents) .build(); return mDriveClient .newCreateFileActivityIntentSender(createFileActivityOptions) .continueWith( task -> { startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0); return null; }); }
Example #9
Source File: CreateFileInAppFolderActivity.java From android-samples with Apache License 2.0 | 5 votes |
private void createFileInAppFolder() { final Task<DriveFolder> appFolderTask = getDriveResourceClient().getAppFolder(); final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents(); Tasks.whenAll(appFolderTask, createContentsTask) .continueWithTask(task -> { DriveFolder parent = appFolderTask.getResult(); DriveContents contents = createContentsTask.getResult(); OutputStream outputStream = contents.getOutputStream(); try (Writer writer = new OutputStreamWriter(outputStream)) { writer.write("Hello World!"); } MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle("New file") .setMimeType("text/plain") .setStarred(true) .build(); return getDriveResourceClient().createFile(parent, changeSet, contents); }) .addOnSuccessListener(this, driveFile -> { showMessage(getString(R.string.file_created, driveFile.getDriveId().encodeToString())); finish(); }) .addOnFailureListener(this, e -> { Log.e(TAG, "Unable to create file", e); showMessage(getString(R.string.file_create_error)); finish(); }); }
Example #10
Source File: RetrieveContentsActivity.java From android-samples with Apache License 2.0 | 5 votes |
private void retrieveContents(DriveFile file) { // [START drive_android_open_file] Task<DriveContents> openFileTask = getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY); // [END drive_android_open_file] // [START drive_android_read_contents] openFileTask .continueWithTask(task -> { DriveContents contents = task.getResult(); // Process contents... // [START_EXCLUDE] // [START drive_android_read_as_string] try (BufferedReader reader = new BufferedReader( new InputStreamReader(contents.getInputStream()))) { StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } showMessage(getString(R.string.content_loaded)); mFileContents.setText(builder.toString()); } // [END drive_android_read_as_string] // [END_EXCLUDE] // [START drive_android_discard_contents] Task<Void> discardTask = getDriveResourceClient().discardContents(contents); // [END drive_android_discard_contents] return discardTask; }) .addOnFailureListener(e -> { // Handle failure // [START_EXCLUDE] Log.e(TAG, "Unable to read contents", e); showMessage(getString(R.string.read_failed)); finish(); // [END_EXCLUDE] }); // [END drive_android_read_contents] }
Example #11
Source File: RewriteContentsActivity.java From android-samples with Apache License 2.0 | 5 votes |
private void rewriteContents(DriveFile file) { // [START drive_android_open_for_write] Task<DriveContents> openTask = getDriveResourceClient().openFile(file, DriveFile.MODE_WRITE_ONLY); // [END drive_android_open_for_write] // [START drive_android_rewrite_contents] openTask.continueWithTask(task -> { DriveContents driveContents = task.getResult(); try (OutputStream out = driveContents.getOutputStream()) { out.write("Hello world".getBytes()); } // [START drive_android_commit_content] Task<Void> commitTask = getDriveResourceClient().commitContents(driveContents, null); // [END drive_android_commit_content] return commitTask; }) .addOnSuccessListener(this, aVoid -> { showMessage(getString(R.string.content_updated)); finish(); }) .addOnFailureListener(this, e -> { Log.e(TAG, "Unable to update contents", e); showMessage(getString(R.string.content_update_failed)); finish(); }); // [END drive_android_rewrite_contents] }
Example #12
Source File: CreateFileActivity.java From android-samples with Apache License 2.0 | 5 votes |
private void createFile() { // [START drive_android_create_file] final Task<DriveFolder> rootFolderTask = getDriveResourceClient().getRootFolder(); final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents(); Tasks.whenAll(rootFolderTask, createContentsTask) .continueWithTask(task -> { DriveFolder parent = rootFolderTask.getResult(); DriveContents contents = createContentsTask.getResult(); OutputStream outputStream = contents.getOutputStream(); try (Writer writer = new OutputStreamWriter(outputStream)) { writer.write("Hello World!"); } MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle("HelloWorld.txt") .setMimeType("text/plain") .setStarred(true) .build(); return getDriveResourceClient().createFile(parent, changeSet, contents); }) .addOnSuccessListener(this, driveFile -> { showMessage(getString(R.string.file_created, driveFile.getDriveId().encodeToString())); finish(); }) .addOnFailureListener(this, e -> { Log.e(TAG, "Unable to create file", e); showMessage(getString(R.string.file_create_error)); finish(); }); // [END drive_android_create_file] }
Example #13
Source File: MainActivity.java From drive-android-quickstart with Apache License 2.0 | 5 votes |
/** * Creates an {@link IntentSender} to start a dialog activity with configured {@link * CreateFileActivityOptions} for user to create a new photo in Drive. */ private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image) { Log.i(TAG, "New contents created."); // Get an output stream for the contents. OutputStream outputStream = driveContents.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 e) { Log.w(TAG, "Unable to write file contents.", e); } // 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(); // Set up options to configure and display the create file activity. CreateFileActivityOptions createFileActivityOptions = new CreateFileActivityOptions.Builder() .setInitialMetadata(metadataChangeSet) .setInitialDriveContents(driveContents) .build(); return mDriveClient .newCreateFileActivityIntentSender(createFileActivityOptions) .continueWith( new Continuation<IntentSender, Void>() { @Override public Void then(@NonNull Task<IntentSender> task) throws Exception { startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0); return null; } }); }
Example #14
Source File: DriveSyncService.java From Passbook with Apache License 2.0 | 5 votes |
@Override public void send(byte[] data) { if(data != null) { mData = data; if (mDriveResourceClient == null) { mListener.onSyncFailed(CA.AUTH); return; } Task<DriveContents> contentsTask; if (mDriveId == null) { contentsTask = mDriveResourceClient.getAppFolder() .continueWithTask(t -> { MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle(SAVED_DATA) .setMimeType("application/bin") .build(); DriveFile file = mDriveResourceClient.createFile(t.getResult(), changeSet, null).getResult(); mDriveId = file.getDriveId(); return mDriveResourceClient.openFile(file, DriveFile.MODE_WRITE_ONLY); }); } else { contentsTask = mDriveResourceClient.openFile(mDriveId.asDriveFile(), DriveFile.MODE_WRITE_ONLY); } contentsTask .continueWithTask(t -> { DriveContents contents = t.getResult(); OutputStream outputStream = contents.getOutputStream(); outputStream.write(mData); return mDriveResourceClient.commitContents(contents, null); }) .addOnFailureListener(e -> mListener.onSyncFailed(CA.DATA_SENT)) .addOnSuccessListener(s -> mListener.onSyncProgress(CA.DATA_SENT)); } }
Example #15
Source File: RetrieveDriveFileContentsAsyncTask.java From faceswap with Apache License 2.0 | 5 votes |
@Override protected String doInBackgroundConnected(DriveId... params) { String state = null; DriveFile file = params[0].asDriveFile(); DriveApi.DriveContentsResult driveContentsResult = file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await(); if (!driveContentsResult.getStatus().isSuccess()) { return null; } DriveContents driveContents = driveContentsResult.getDriveContents(); BufferedReader reader = new BufferedReader( new InputStreamReader(driveContents.getInputStream())); StringBuilder builder = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); } state = builder.toString(); reader.close(); } catch (IOException e) { Log.e(TAG, "IOException while reading from the stream", e); } driveContents.discard(getGoogleApiClient()); String validState=UIUtils.stripMagicSequence(state); return validState; }
Example #16
Source File: RemoteBackup.java From Database-Backup-Restore with Apache License 2.0 | 5 votes |
private Task<Void> createFileIntentSender(DriveContents driveContents) { final String inFileName = activity.getDatabasePath(DATABASE_NAME).toString(); try { File dbFile = new File(inFileName); FileInputStream fis = new FileInputStream(dbFile); OutputStream outputStream = driveContents.getOutputStream(); // Transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder() .setTitle("database_backup.db") .setMimeType("application/db") .build(); CreateFileActivityOptions createFileActivityOptions = new CreateFileActivityOptions.Builder() .setInitialMetadata(metadataChangeSet) .setInitialDriveContents(driveContents) .build(); return mDriveClient .newCreateFileActivityIntentSender(createFileActivityOptions) .continueWith( task -> { activity.startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATION, null, 0, 0, 0); return null; }); }
Example #17
Source File: GoogleDriveService.java From WheelLogAndroid with GNU General Public License v3.0 | 5 votes |
@Override public void onResult(@NonNull DriveApi.DriveContentsResult result) { if (!result.getStatus().isSuccess()) { Timber.i("Error while trying to create new file contents"); exitUploadFailed(); return; } final DriveContents driveContents = result.getDriveContents(); updateNotification("Uploading file " + file.getName()); // write content to DriveContents OutputStream outputStream = driveContents.getOutputStream(); Writer writer = new OutputStreamWriter(outputStream); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) writer.append(line).append('\r'); br.close(); writer.close(); } catch (IOException e) { Timber.e(e.getMessage()); } MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle(file.getName()) .setMimeType("text/plain") .setStarred(true).build(); // create a file in "WheelLog Logs" folder folderDriveId.asDriveFolder() .createFile(getGoogleApiClient(), changeSet, driveContents) .setResultCallback(fileCreatedCallback); }
Example #18
Source File: DriveSyncService.java From Passbook with Apache License 2.0 | 4 votes |
@Override public void read() { if (mDriveResourceClient == null) { mListener.onSyncFailed(CA.CONNECTION); } final Task<DriveFolder> appFolderTask = mDriveResourceClient.getAppFolder(); final Query query = new Query.Builder().build(); appFolderTask.continueWithTask(t -> mDriveResourceClient.queryChildren(t.getResult(), query)) .continueWithTask(t -> { Task<DriveContents> contentsTask = null; for (Metadata metadata : t.getResult()) { if (SAVED_DATA.equalsIgnoreCase(metadata.getTitle())) { mDriveId = metadata.getDriveId(); contentsTask= mDriveResourceClient.openFile(mDriveId.asDriveFile(), DriveFile.MODE_READ_ONLY); break; } } if (contentsTask == null) { return mDriveResourceClient.createContents(); } return contentsTask; }) .addOnSuccessListener(c -> { try { InputStream fis = c.getInputStream(); if (fis.available() < 1) { throw new IOException(); } mData = new byte[fis.available()]; int totalBytesRead = fis.read(mData); fis.close(); if (totalBytesRead < mData.length) { throw new IOException(); } mListener.onSyncProgress(CA.DATA_RECEIVED); } catch (IllegalStateException | IOException e) { Log.e(LOG_TAG, "read: ", e.getCause()); mListener.onSyncFailed(CA.NO_DATA); } }) .addOnFailureListener(f -> mListener.onSyncFailed(CA.NO_DATA)); }
Example #19
Source File: CreateFileWithCreatorActivity.java From android-samples with Apache License 2.0 | 4 votes |
private void createFileWithIntent() { // [START drive_android_create_file_with_intent] Task<DriveContents> createContentsTask = getDriveResourceClient().createContents(); createContentsTask .continueWithTask(task -> { DriveContents contents = task.getResult(); OutputStream outputStream = contents.getOutputStream(); try (Writer writer = new OutputStreamWriter(outputStream)) { writer.write("Hello World!"); } MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setTitle("New file") .setMimeType("text/plain") .setStarred(true) .build(); CreateFileActivityOptions createOptions = new CreateFileActivityOptions.Builder() .setInitialDriveContents(contents) .setInitialMetadata(changeSet) .build(); return getDriveClient().newCreateFileActivityIntentSender(createOptions); }) .addOnSuccessListener(this, intentSender -> { try { startIntentSenderForResult( intentSender, REQUEST_CODE_CREATE_FILE, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Unable to create file", e); showMessage(getString(R.string.file_create_error)); finish(); } }) .addOnFailureListener(this, e -> { Log.e(TAG, "Unable to create file", e); showMessage(getString(R.string.file_create_error)); finish(); }); // [END drive_android_create_file_with_intent] }
Example #20
Source File: AppendContentsActivity.java From android-samples with Apache License 2.0 | 4 votes |
private void appendContents(DriveFile file) { // [START drive_android_open_for_append] Task<DriveContents> openTask = getDriveResourceClient().openFile(file, DriveFile.MODE_READ_WRITE); // [END drive_android_open_for_append] // [START drive_android_append_contents] openTask.continueWithTask(task -> { DriveContents driveContents = task.getResult(); ParcelFileDescriptor pfd = driveContents.getParcelFileDescriptor(); long bytesToSkip = pfd.getStatSize(); try (InputStream in = new FileInputStream(pfd.getFileDescriptor())) { // Skip to end of file while (bytesToSkip > 0) { long skipped = in.skip(bytesToSkip); bytesToSkip -= skipped; } } try (OutputStream out = new FileOutputStream(pfd.getFileDescriptor())) { out.write("Hello world".getBytes()); } // [START drive_android_commit_contents_with_metadata] MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .setStarred(true) .setLastViewedByMeDate(new Date()) .build(); Task<Void> commitTask = getDriveResourceClient().commitContents(driveContents, changeSet); // [END drive_android_commit_contents_with_metadata] return commitTask; }) .addOnSuccessListener(this, aVoid -> { showMessage(getString(R.string.content_updated)); finish(); }) .addOnFailureListener(this, e -> { Log.e(TAG, "Unable to update contents", e); showMessage(getString(R.string.content_update_failed)); finish(); }); // [END drive_android_append_contents] }
Example #21
Source File: RemoteBackup.java From Database-Backup-Restore with Apache License 2.0 | 4 votes |
private void retrieveContents(DriveFile file) { //DB Path final String inFileName = activity.getDatabasePath(DATABASE_NAME).toString(); Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY); openFileTask .continueWithTask(task -> { DriveContents contents = task.getResult(); try { ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor(); FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor()); // Open the empty db as the output stream OutputStream output = new FileOutputStream(inFileName); // Transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = fileInputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } // Close the streams output.flush(); output.close(); fileInputStream.close(); Toast.makeText(activity, "Import completed", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(activity, "Error on import", Toast.LENGTH_SHORT).show(); } return mDriveResourceClient.discardContents(contents); }) .addOnFailureListener(e -> { Log.e(TAG, "Unable to read contents", e); Toast.makeText(activity, "Error on import", Toast.LENGTH_SHORT).show(); }); }
Example #22
Source File: ConflictResolver.java From android-samples with Apache License 2.0 | 4 votes |
/** * Initiate the resolution process by connecting the GoogleApiClient. */ void resolve() { // [START drive_android_resolve_conflict] // A new DriveResourceClient should be created to handle each new CompletionEvent since each // event is tied to a specific user account. Any DriveFile action taken must be done using // the correct account. GoogleSignInOptions.Builder signInOptionsBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(Drive.SCOPE_FILE) .requestScopes(Drive.SCOPE_APPFOLDER); if (mConflictedCompletionEvent.getAccountName() != null) { signInOptionsBuilder.setAccountName(mConflictedCompletionEvent.getAccountName()); } GoogleSignInClient signInClient = GoogleSignIn.getClient(mContext, signInOptionsBuilder.build()); signInClient.silentSignIn() .continueWith(mExecutorService, (Continuation<GoogleSignInAccount, Void>) signInTask -> { mDriveResourceClient = Drive.getDriveResourceClient( mContext, signInTask.getResult()); mBaseContent = ConflictUtil.getStringFromInputStream( mConflictedCompletionEvent.getBaseContentsInputStream()); mModifiedContent = ConflictUtil.getStringFromInputStream( mConflictedCompletionEvent .getModifiedContentsInputStream()); return null; }) .continueWithTask(mExecutorService, task -> { DriveId driveId = mConflictedCompletionEvent.getDriveId(); return mDriveResourceClient.openFile( driveId.asDriveFile(), DriveFile.MODE_READ_ONLY); }) .continueWithTask(mExecutorService, task -> { mDriveContents = task.getResult(); InputStream serverInputStream = task.getResult().getInputStream(); mServerContent = ConflictUtil.getStringFromInputStream(serverInputStream); return mDriveResourceClient.reopenContentsForWrite(mDriveContents); }) .continueWithTask(mExecutorService, task -> { DriveContents contentsForWrite = task.getResult(); mResolvedContent = ConflictUtil.resolveConflict( mBaseContent, mServerContent, mModifiedContent); OutputStream outputStream = contentsForWrite.getOutputStream(); try (Writer writer = new OutputStreamWriter(outputStream)) { writer.write(mResolvedContent); } // It is not likely that resolving a conflict will result in another // conflict, but it can happen if the file changed again while this // conflict was resolved. Since we already implemented conflict // resolution and we never want to miss user data, we commit here // with execution options in conflict-aware mode (otherwise we would // overwrite server content). ExecutionOptions executionOptions = new ExecutionOptions.Builder() .setNotifyOnCompletion(true) .setConflictStrategy( ExecutionOptions .CONFLICT_STRATEGY_KEEP_REMOTE) .build(); // Commit resolved contents. MetadataChangeSet modifiedMetadataChangeSet = mConflictedCompletionEvent.getModifiedMetadataChangeSet(); return mDriveResourceClient.commitContents(contentsForWrite, modifiedMetadataChangeSet, executionOptions); }) .addOnSuccessListener(aVoid -> { mConflictedCompletionEvent.dismiss(); Log.d(TAG, "resolved list"); sendResult(mModifiedContent); }) .addOnFailureListener(e -> { // The contents cannot be reopened at this point, probably due to // connectivity, so by snoozing the event we will get it again later. Log.d(TAG, "Unable to write resolved content, snoozing completion event.", e); mConflictedCompletionEvent.snooze(); if (mDriveContents != null) { mDriveResourceClient.discardContents(mDriveContents); } }); // [END drive_android_resolve_conflict] }
Example #23
Source File: DatabaseImport.java From financisto with GNU General Public License v2.0 | 4 votes |
public static DatabaseImport createFromGoogleDriveBackup(Context context, DatabaseAdapter db, DriveContents driveFileContents) throws IOException { InputStream inputStream = driveFileContents.getInputStream(); InputStream in = new GZIPInputStream(inputStream); return new DatabaseImport(context, db, in); }