Skip to content Skip to sidebar Skip to footer

Google Drive Api Migration To Rest Api

Since Google is deprecating the Android API, I am trying to migrate to REST API. My app uses Google Drive to save User's data. The User have two options for backup (manual and sche

Solution 1:

First you need to sign in the user:

GoogleSignInOptionssignInOptions=newGoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestScopes(newScope(DriveScopes.DRIVE_FILE))
            .build();
    GoogleSignInClientclient= GoogleSignIn.getClient(activity, signInOptions);

    // The result of the sign-in Intent is handled in onActivityResult
    startActivityForResult(client.getSignInIntent(), RC_CODE_SIGN_IN);

In the onActivityResult:

GoogleSignIn.getSignedInAccountFromIntent(result)
                .addOnSuccessListener(newOnSuccessListener<GoogleSignInAccount>() {
                    @OverridepublicvoidonSuccess(GoogleSignInAccount googleSignInAccount) {
                        HyperLog.i(TAG, "Signed in as " + googleSignInAccount.getEmail());
                        mDriveServiceHelper = getDriveServiceHelper(googleSignInAccount);
                    }
                })
                .addOnFailureListener(newOnFailureListener() {
                    @OverridepublicvoidonFailure(@NonNull Exception e) {
                        HyperLog.e(TAG, "Unable to sign in!", e);
                    }
                });

Ones the user was signed in you can retrieve the last Google Sign In Account with:

GoogleSignInAccountaccount= GoogleSignIn.getLastSignedInAccount(getActivity());

And to get your DriveServiceHelper you can use the account you have retrieved:

mDriveServiceHelper = getDriveServiceHelper(account);

The "getDriveServiceHelper" method looks like this:

private DriveServiceHelper getDriveServiceHelper(GoogleSignInAccount googleSignInAccount) {
        // Use the authenticated account ot sign in to the Drive serviceGoogleAccountCredentialcredential= GoogleAccountCredential.usingOAuth2(
                activity, Collections.singleton(DriveScopes.DRIVE_FILE));
        credential.setSelectedAccount(googleSignInAccount.getAccount());

        DrivegoogleDriveService=newDrive.Builder(AndroidHttp.newCompatibleTransport(),
                newGsonFactory(), credential)
                .setApplicationName("COL Reminder")
                .build();
        returnnewDriveServiceHelper(googleDriveService);
    }

Post a Comment for "Google Drive Api Migration To Rest Api"