com.google.android.gms.drive.DriveId Java Examples

The following examples show how to use com.google.android.gms.drive.DriveId. 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: BaseDemoActivity.java    From android-samples with Apache License 2.0 7 votes vote down vote up
/**
 * Handles resolution callbacks.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CODE_SIGN_IN:
            if (resultCode != RESULT_OK) {
                // Sign-in may fail or be cancelled by the user. For this sample, sign-in is
                // required and is fatal. For apps where sign-in is optional, handle
                // appropriately
                Log.e(TAG, "Sign-in failed.");
                finish();
                return;
            }

            Task<GoogleSignInAccount> getAccountTask =
                GoogleSignIn.getSignedInAccountFromIntent(data);
            if (getAccountTask.isSuccessful()) {
                initializeDriveClient(getAccountTask.getResult());
            } else {
                Log.e(TAG, "Sign-in failed.");
                finish();
            }
            break;
        case REQUEST_CODE_OPEN_ITEM:
            if (resultCode == RESULT_OK) {
                DriveId driveId = data.getParcelableExtra(
                        OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
                mOpenItemTaskSource.setResult(driveId);
            } else {
                mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example #2
Source File: MainActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the list from Drive if it exists. If not, create a new list.
 */
private Task<Void> initializeGroceryList() {
    Log.d(TAG, "Locating grocery list file.");
    Query query = new Query.Builder()
                          .addFilter(Filters.eq(SearchableField.TITLE,
                                  getResources().getString(R.string.groceryListFileName)))
                          .build();
    return getDriveResourceClient()
            .query(query)
            .continueWithTask(task -> {
                MetadataBuffer metadataBuffer = task.getResult();
                try {
                    if (metadataBuffer.getCount() == 0) {
                        return createNewFile();
                    } else {
                        DriveId id = metadataBuffer.get(0).getDriveId();
                        return Tasks.forResult(id.asDriveFile());
                    }
                } finally {
                    metadataBuffer.release();
                }
            })
            .continueWithTask(task -> loadContents(task.getResult()));
}
 
Example #3
Source File: MainActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the folder view after the given task completes.
 *
 * @return Task which resolves after the view has been initialized
 */
private Task<Void> initializeFolderView() {
    Task<DriveFolder> folderTask;
    if (mNavigationPath.isEmpty()) {
        folderTask = mDriveResourceClient.getRootFolder();
    } else {
        folderTask = Tasks.forResult(mNavigationPath.peek().asDriveFolder());
    }
    Task<Void> initFolderTask = folderTask.continueWith(task -> {
        DriveId id = task.getResult().getDriveId();
        if (mNavigationPath.isEmpty()) {
            mNavigationPath.push(id);
        }
        return null;
    });
    return updateUiAfterTask(initFolderTask);
}
 
Example #4
Source File: TheHubActivity.java    From ToDay with MIT License 6 votes vote down vote up
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case AppConstants.EXPORT_RESOLVE_CONNECTION_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
//                    mGoogleApiClient.connect();
                }
                break;
            case AppConstants.EXPORT_CREATOR_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    DriveId driveFileId = (DriveId) data.getParcelableExtra(
                            OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
                    writeDataExportToFile(driveFileId);
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }
 
Example #5
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@DebugLog
private void readFileFromDrive(final MetadataBuffer meta_data, final DriveId drive_id) {
    Drive.DriveApi.getFile(_parent.getClient(), drive_id)
            .open(_parent.getClient(), DriveFile.MODE_READ_ONLY, null)
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
                @Override
                public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
                    try {
                        InputStream input = driveContentsResult.getDriveContents()
                                .getInputStream();
                        String total = consumeStream(input);

                        AmiiboFile amiibo_file = AmiiboFile.fromString(total.toString());
                        _parent.onFileRead(amiibo_file);
                        if (!meta_data.isClosed()) meta_data.release();
                    } catch (IOException e) {
                        e.printStackTrace();
                        _parent.onFileRead(null);
                    }
                }
            });
}
 
Example #6
Source File: ActivityUtils.java    From CumulusTV with MIT License 5 votes vote down vote up
private static void actuallyWriteData(final Context context, GoogleApiClient gapi) {
        DriveSettingsManager sm = new DriveSettingsManager(context);
        sm.setGoogleDriveSyncable(gapi, new DriveSettingsManager.GoogleDriveListener() {
            @Override
            public void onActionFinished(boolean cloudToLocal) {
                Log.d(TAG, "Action finished " + cloudToLocal);
            }
        });
        try {
            sm.writeToGoogleDrive(DriveId.decodeFromString(sm.getString(R.string.sm_google_drive_id)),
                    ChannelDatabase.getInstance(context).toString());
            GoogleDriveBroadcastReceiver.changeStatus(context,
                    GoogleDriveBroadcastReceiver.EVENT_UPLOAD_COMPLETE);

            final String info = TvContract.buildInputId(TV_INPUT_SERVICE);
            CumulusJobService.requestImmediateSync1(context, info, CumulusJobService.DEFAULT_IMMEDIATE_EPG_DURATION_MILLIS,
                    new ComponentName(context, CumulusJobService.class));
            Log.d(TAG, "Data actually written");
//            Toast.makeText(context, "Channels uploaded", Toast.LENGTH_SHORT).show();
        } catch(Exception e) {
            // Probably invalid drive id. No worries, just let someone know
            Log.e(TAG, e.getMessage() + "");
            Toast.makeText(context, R.string.invalid_file,
                    Toast.LENGTH_SHORT).show();
        }
    }
 
Example #7
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Prompts the user to select a folder using OpenFileActivity.
 *
 * @param openOptions Filter that should be applied to the selection
 * @return Task that resolves with the selected item's ID.
 */
private Task<DriveId> pickItem(OpenFileActivityOptions openOptions) {
    mOpenItemTaskSource = new TaskCompletionSource<>();
    getDriveClient()
            .newOpenFileActivityIntentSender(openOptions)
            .continueWith((Continuation<IntentSender, Void>) task -> {
                startIntentSenderForResult(
                        task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
                return null;
            });
    return mOpenItemTaskSource.getTask();
}
 
Example #8
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Prompts the user to select a folder using OpenFileActivity.
 *
 * @return Task that resolves with the selected item's ID.
 */
protected Task<DriveId> pickFolder() {
    OpenFileActivityOptions openOptions =
            new OpenFileActivityOptions.Builder()
                    .setSelectionFilter(
                            Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE))
                    .setActivityTitle(getString(R.string.select_folder))
                    .build();
    return pickItem(openOptions);
}
 
Example #9
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Prompts the user to select a text file using OpenFileActivity.
 *
 * @return Task that resolves with the selected item's ID.
 */
protected Task<DriveId> pickTextFile() {
    OpenFileActivityOptions openOptions =
            new OpenFileActivityOptions.Builder()
                    .setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "text/plain"))
                    .setActivityTitle(getString(R.string.select_file))
                    .build();
    return pickItem(openOptions);
}
 
Example #10
Source File: CreateFileWithCreatorActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_CREATE_FILE) {
        if (resultCode != RESULT_OK) {
            Log.e(TAG, "Unable to create file");
            showMessage(getString(R.string.file_create_error));
        } else {
            DriveId driveId =
                    data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
            showMessage(getString(R.string.file_created, "File created with ID: " + driveId));
        }
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example #11
Source File: DriveSettingsManager.java    From CumulusTV with MIT License 5 votes vote down vote up
/**
 * Writes some data to a Google Drive file, this can get from a preference
 * @param driveId The id of the file to be written to
 * @param data The string of data that should be written
 */
public void writeToGoogleDrive(DriveId driveId, String data) {
    DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
    if (DEBUG) {
        Log.d(TAG, "Writing to " + driveId + " -> " + data);
    }
    new EditGoogleDriveAsyncTask(mContext).execute(file, data);
}
 
Example #12
Source File: ActivityUtils.java    From CumulusTV with MIT License 5 votes vote down vote up
public static void deleteChannelData(final Activity activity, GoogleApiClient gapi) {
    final DriveSettingsManager sm = new DriveSettingsManager(activity);
    sm.setGoogleDriveSyncable(gapi, null);
    new AlertDialog.Builder(activity)
            .setTitle(R.string.title_delete_all_channels)
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    ChannelDatabase.getInstance(activity).eraseData();
                    GoogleDriveBroadcastReceiver.changeStatus(activity,
                            GoogleDriveBroadcastReceiver.EVENT_DOWNLOAD_COMPLETE);
                    if (CloudStorageProvider.getInstance().isDriveConnected()) {
                        try {
                            DriveId did = DriveId.decodeFromString(sm.getString(R.string.sm_google_drive_id));
                            sm.writeToGoogleDrive(did,
                                    sm.getString(ChannelDatabase.KEY));
                        } catch (Exception e) {
                            Toast.makeText(activity, R.string.toast_error_driveid_invalid,
                                    Toast.LENGTH_SHORT).show();
                        }
                        sm.setString(R.string.sm_google_drive_id, "");
                    }
                    Toast.makeText(activity, R.string.toast_msg_channels_deleted,
                            Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton(R.string.no, null)
            .show();
}
 
Example #13
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private DriveFolder getOrCreateDriveFolder(String targetFolder) throws IOException {
    Query query = new Query.Builder().addFilter(Filters.and(
            Filters.eq(SearchableField.TRASHED, false),
            Filters.eq(SearchableField.TITLE, targetFolder),
            Filters.eq(SearchableField.MIME_TYPE, "application/vnd.google-apps.folder")
    )).build();
    DriveApi.MetadataBufferResult result = Drive.DriveApi.query(googleApiClient, query).await();
    if (result.getStatus().isSuccess()) {
        DriveId driveId = fetchDriveId(result);
        if (driveId != null) {
            return Drive.DriveApi.getFolder(googleApiClient, driveId);
        }
    }
    return createDriveFolder(targetFolder);
}
 
Example #14
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void listElements(final TGBrowserCallBack<List<TGBrowserElement>> cb) {
	try {
		if( this.folder != null ) {
			this.folder.getFolder().listChildren(this.client).setResultCallback(new ResultCallback<MetadataBufferResult>() {
				public void onResult(MetadataBufferResult result) {
		            if( result.getStatus().isSuccess() ) {
		            	List<TGBrowserElement> elements = new ArrayList<TGBrowserElement>();
		            	
		            	Iterator<Metadata> it = result.getMetadataBuffer().iterator();
		            	while(it.hasNext()) {
		            		Metadata metadata = it.next();
		            		DriveId driveId = metadata.getDriveId();
		            		String name = metadata.getTitle();
		            		
		            		if(!metadata.isTrashed() && !metadata.isExplicitlyTrashed()) {
			            		if( metadata.isFolder() ) {
			            			elements.add(new TGDriveBrowserFolder(TGDriveBrowser.this.folder, Drive.DriveApi.getFolder(TGDriveBrowser.this.client, driveId), name));
			            		} else {
			            			elements.add(new TGDriveBrowserFile(TGDriveBrowser.this.folder, Drive.DriveApi.getFile(TGDriveBrowser.this.client, driveId), name));
			            		}
		            		}
		            	}
		            	
						if( !elements.isEmpty() ){
							Collections.sort(elements, new TGBrowserElementComparator());
						}
						
		            	cb.onSuccess(elements);
		            } else {
		            	cb.handleError(new TGBrowserException(findActivity().getString(R.string.gdrive_list_children_error)));
		            }
				};
			});
		} else {
			cb.onSuccess(new ArrayList<TGBrowserElement>());
		}
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example #15
Source File: RetrieveDriveFileContentsAsyncTask.java    From faceswap with Apache License 2.0 5 votes vote down vote up
@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: CloudletDemoActivity.java    From faceswap with Apache License 2.0 5 votes vote down vote up
private void openDriveFile(DriveId mSelectedFileDriveId) {
    // Reset progress dialog back to zero as we're
    // initiating an opening request.
    RetrieveDriveFileContentsAsyncTask task=
            new RetrieveDriveFileContentsAsyncTask(getApplicationContext(),
                    gdriveCallBack);
    task.execute(mSelectedFileDriveId);
}
 
Example #17
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
private Task<DriveId> pickFile() {
    OpenFileActivityOptions openOptions =
            new OpenFileActivityOptions.Builder()
                    .setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "application/db"))
                    .setActivityTitle("Select DB File")
                    .build();
    return pickItem(openOptions);
}
 
Example #18
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
private Task<DriveId> pickItem(OpenFileActivityOptions openOptions) {
    mOpenItemTaskSource = new TaskCompletionSource<>();
    mDriveClient
            .newOpenFileActivityIntentSender(openOptions)
            .continueWith((Continuation<IntentSender, Void>) task -> {
                activity.startIntentSenderForResult(
                        task.getResult(), REQUEST_CODE_OPENING, null, 0, 0, 0);
                return null;
            });
    return mOpenItemTaskSource.getTask();
}
 
Example #19
Source File: MainActivity.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {

        case REQUEST_CODE_SIGN_IN:
            Log.i(TAG, "Sign in request code");
            // Called after user is signed in.
            if (resultCode == RESULT_OK) {
                remoteBackup.connectToDrive(isBackup);
            }
            break;

        case REQUEST_CODE_CREATION:
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Backup successfully saved.");
                Toast.makeText(this, "Backup successufly loaded!", Toast.LENGTH_SHORT).show();
            }
            break;

        case REQUEST_CODE_OPENING:
            if (resultCode == RESULT_OK) {
                DriveId driveId = data.getParcelableExtra(
                        OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
                remoteBackup.mOpenItemTaskSource.setResult(driveId);
            } else {
                remoteBackup.mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
            }

    }
}
 
Example #20
Source File: TheHubActivity.java    From ToDay with MIT License 5 votes vote down vote up
private void writeDataExportToFile(DriveId driveFileId) {
    EditContentParams params = new EditContentParams(
            new ExportDataManager(TheHubActivity.this).readFileByInputStream(),
            driveFileId.asDriveFile()
    );

    new EditContentsAsyncTask(this).execute(params);

}
 
Example #21
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private DriveId fetchDriveId(DriveApi.MetadataBufferResult result) {
    MetadataBuffer buffer = result.getMetadataBuffer();
    try {
        for (Metadata metadata : buffer) {
            if (metadata == null) continue;
            return metadata.getDriveId();
        }
    } finally {
        buffer.close();
    }
    return null;
}
 
Example #22
Source File: DriveSettingsManager.java    From CumulusTV with MIT License 4 votes vote down vote up
public void readFromGoogleDrive(DriveId driveId, final int resId) {
    readFromGoogleDrive(driveId, mContext.getString(resId));
}
 
Example #23
Source File: CloudletDemoActivity.java    From faceswap with Apache License 2.0 4 votes vote down vote up
/**
 * file picker activie result
 * @param requestCode
 * @param resultCode
 * @param data
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode){
        case FilePickerActivity.REQUEST_FILE:
            if (resultCode==RESULT_OK){
                Bundle extras = data.getExtras();
                String path = (String) extras.get(FilePickerActivity.FILE_EXTRA_DATA_PATH);
                Log.d(TAG, "path: " + path);
                boolean isLoad=(boolean)extras.get(FilePickerActivity.INTENT_EXTRA_ACTION_READ);
                File file=new File(path);
                if (isLoad){
                    byte[] stateData= UIUtils.loadFromFile(file);
                    if (stateData!=null){
                        actionUploadStateByteArray(stateData);
                    } else {
                        Toast.makeText(this, "Invalid File",Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (this.asyncResponseExtra!=null){
                        UIUtils.saveToFile(file, this.asyncResponseExtra);
                    }
                }
            }
            break;
        case GDRIVE_RESOLVE_CONNECTION_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "drive client problem resolved. Trying to connect");
                mGoogleApiClient.connect();
            } else {
                //if not okay, then give up
                pendingGDriveAction=-1;
                Log.i(TAG, "drive connection resolution failed");
                Toast.makeText(this,"Failed to Connect Google Drive", Toast.LENGTH_LONG).show();
            }
            break;
        case GDRIVE_REQUEST_CODE_OPENER:
            if (resultCode == RESULT_OK) {
                DriveId fileId = (DriveId) data.getParcelableExtra(
                        OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
                Log.i(TAG, "user select drive file id: "+fileId);
                openDriveFile(fileId);
            }
            break;
        case GDRIVE_REQUEST_CODE_CREATOR:
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Image successfully saved.");
                Toast.makeText(this,
                        "succesfully saved to google drive", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}
 
Example #24
Source File: DriveFileInfo.java    From financisto with GNU General Public License v2.0 4 votes vote down vote up
public DriveFileInfo(DriveId driveId, String title, Date createdDate) {
    this.driveId = driveId;
    this.title = title;
    this.createdDate = createdDate;
}
 
Example #25
Source File: MainActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
private void navigateToFolder(DriveId folderId) {
    setUiInteractionsEnabled(false);
    mNavigationPath.push(folderId);
    Task<Void> navigationTask = updateUiAfterTask(Tasks.forResult(null));
    handleTaskError(navigationTask, R.string.change_folder_error);
}
 
Example #26
Source File: ConflictResolver.java    From android-samples with Apache License 2.0 4 votes vote down vote up
/**
 * 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 #27
Source File: DriveFio.java    From Drive-Database-Sync with Apache License 2.0 3 votes vote down vote up
/**
 * Work method that retrieves a DriveFile from some passed Metadata.
 * @param driveClient the {@link GoogleApiClient} to use for this Drive request
 * @param metadata the Metadata to pull the {@link DriveFile} out of
 * @return the {@link DriveFile} extracted from the passed Metadata
 */
public DriveFile getDriveFileFromMetadata(GoogleApiClient driveClient, Metadata metadata) {

    DriveId driveId = metadata.getDriveId();

    return Drive.DriveApi.getFile(driveClient, driveId);
}