Google Drive REST API for android
Google Drive REST API for android
This is a simple wrapper of around Google Drive REST API using OKHTTP.
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.tejpratap46:Google-Drive-REST-Android:VERSION'
}
Before you can do any request, you need to authenticate your app with google drive, Best way is to use Google Sign In For Android with Offline Access
In Your Android App code, Auth using offline access, code:
String serverClientId = "CLIENT_ID_OF_WEB_BROWSER_API";
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
.requestServerAuthCode(serverClientId)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_GOOGLE_SIGN_IN);
In your onActivityResult(Intent data)
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
String authCode = account.getServerAuthCode();
ArrayList<GDAuthConfig.SCOPES> scopes = new ArrayList<>();
scopes.add(GDAuthConfig.SCOPES.EMAIL);
scopes.add(GDAuthConfig.SCOPES.DRIVE);
scopes.add(GDAuthConfig.SCOPES.APP_FOLDER);
final GDAuthConfig gdAuthConfig = new GDAuthConfig(REDIRECT_URI, CLIENT_ID, CLIENT_SECRET, scopes);
// Use auth code to get AccessToken
GDApiManager.getInstance().getAuthFromCodeAsync(authCode, gdAuthConfig, new GDAuthResponse.OnAuthResponseListener() {
@Override
public void onSuccess(final GDAuthResponse gdAuthResponse) {
boolean isAuthDataSaved = GDAuthManager.getInstance().setAuthData(MainActivity.this, gdAuthResponse);
}
@Override
public void onError(GDException exception) {
}
});
} catch (ApiException e) {
Log.w(TAG, "Sign-in failed", e);
updateUI(null);
}
GDAuthResponse gdAuthResponse = getAuthFromCode(authCode, gdAuthConfig);
GDAuthResponse gdAuthResponse = getAuthFromRefreshToken(context, authCode, previousAuthResponse);
GDUserInfo gdUserInfo = getUserInfo(context, gdAuthResponse, gdAuthConfig);
GDUploadFileResponse fileUploadResponse = uploadFile(context, gdAuthResponse, gdAuthConfig, fileToUpload, fileMime, uploadToAppFolder);
File downloadedFile = downloadFile(context, gdAuthResponse, gdAuthConfig, gdResourceId, fileName)
boolnea isFileDeleted = deleteFile(context, gdAuthResponse, gdAuthConfig, gdResourceId)
Fo example, look into MainActivity of app module