├── .gitignore ├── GoogleDriveSaveSample.iml ├── README.md ├── app ├── .gitignore ├── app.iml ├── build.gradle ├── google-services.json ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── sample │ │ └── google │ │ └── drive │ │ ├── app │ │ ├── App.java │ │ └── AppActivity.java │ │ ├── data │ │ ├── DBConstants.java │ │ ├── DatabaseOpenHelper.java │ │ └── InfoRepository.java │ │ ├── google │ │ ├── GoogleDriveActivity.java │ │ ├── GoogleDriveApiDataRepository.java │ │ └── GoogleSignInActivity.java │ │ ├── ui │ │ └── MainActivity.java │ │ └── util │ │ ├── ByteSegments.java │ │ ├── FileInputSource.java │ │ ├── IOUtils.java │ │ └── InputSource.java │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ └── activity_main.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── cert └── debug.keystore ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── img └── img.png ├── local.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | 10 | # Mainframer configs 11 | .mainframer/ 12 | 13 | # fastline 14 | /fastlane/report.xml 15 | 16 | # keystore 17 | /cert/release.keystore 18 | /cert/release.properties 19 | 20 | /release_notes.txt 21 | /fastlane/Appfile 22 | -------------------------------------------------------------------------------- /GoogleDriveSaveSample.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # google-drive-api-sample 2 | 3 | This is sample based on Google Drive API. Simple use case — using Google Drive to backup and restore SQLite Database. 4 | 5 | 6 | ### Overview 7 | 8 | This example uses Java, SQLite DB, Google Sign In, Google Drive API, Constraint Layout. The app connects to Google Drive to backup and restore SQLite Database. This case uses a private directory (application directory) of Google Drive and the owner of Google Drive cannot get access to this folder only the app can do this. This example can help you if you want to save application info and you don't have backend or other storage. Google Drive is free storage and this solution can save your money. 9 | 10 | 11 | ### Requirements 12 | 13 | - Connected Google Play services on a phone 14 | - Google account to access Google Drive 15 | 16 | 17 | ### Use Case 18 | 19 | - Click to input and write text 20 | - Click "Write to database", the app saves your text to the SQLite 21 | - Click "Save to Google Drive", the app uploads your DB to the Google Drive private storage 22 | - Click "Restore from Google Drive", the app downloads your DB from the Google Drive, than restore local DB and shows string from DB in input. 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.3" 8 | 9 | defaultConfig { 10 | applicationId "com.sample.google.drive" 11 | minSdkVersion 25 12 | targetSdkVersion 30 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | signingConfigs { 20 | debug { 21 | storeFile file('../cert/debug.keystore') 22 | } 23 | } 24 | 25 | buildTypes { 26 | release { 27 | minifyEnabled false 28 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 29 | } 30 | } 31 | 32 | compileOptions { 33 | sourceCompatibility JavaVersion.VERSION_1_8 34 | targetCompatibility JavaVersion.VERSION_1_8 35 | } 36 | 37 | packagingOptions { 38 | exclude 'META-INF/DEPENDENCIES' 39 | } 40 | } 41 | 42 | dependencies { 43 | implementation 'androidx.appcompat:appcompat:1.2.0' 44 | implementation 'com.google.android.material:material:1.2.1' 45 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 46 | implementation 'androidx.navigation:navigation-fragment:2.3.2' 47 | implementation 'androidx.navigation:navigation-ui:2.3.2' 48 | 49 | implementation 'com.google.android.gms:play-services-auth:19.0.0' 50 | implementation 'com.google.http-client:google-http-client-gson:1.26.0' 51 | implementation('com.google.api-client:google-api-client-android:1.26.0') { 52 | exclude group: 'org.apache.httpcomponents' 53 | } 54 | implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0') { 55 | exclude group: 'org.apache.httpcomponents' 56 | } 57 | 58 | testImplementation 'junit:junit:4.13.1' 59 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 60 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 61 | } 62 | 63 | apply plugin: 'com.google.gms.google-services' 64 | -------------------------------------------------------------------------------- /app/google-services.json: -------------------------------------------------------------------------------- 1 | { 2 | "project_info": { 3 | "project_number": "605509048106", 4 | "firebase_url": "https://debug-project-1535951998338.firebaseio.com", 5 | "project_id": "debug-project-1535951998338", 6 | "storage_bucket": "debug-project-1535951998338.appspot.com" 7 | }, 8 | "client": [ 9 | { 10 | "client_info": { 11 | "mobilesdk_app_id": "1:605509048106:android:35bdcd6304376035307053", 12 | "android_client_info": { 13 | "package_name": "com.sample.google.drive" 14 | } 15 | }, 16 | "oauth_client": [ 17 | { 18 | "client_id": "605509048106-b8f51689n4e7jrf6rb3oplerfos5a2ev.apps.googleusercontent.com", 19 | "client_type": 1, 20 | "android_info": { 21 | "package_name": "com.sample.google.drive", 22 | "certificate_hash": "553f92c9ccb77ae73128bd1963fcf6d918eddb53" 23 | } 24 | }, 25 | { 26 | "client_id": "605509048106-v1u5udkhv45cq0unvd7ckuqqeei8fpet.apps.googleusercontent.com", 27 | "client_type": 3 28 | } 29 | ], 30 | "api_key": [ 31 | { 32 | "current_key": "AIzaSyDOXtJJYYQN62z5UKC9YJPbeqbYabCpakc" 33 | } 34 | ], 35 | "services": { 36 | "appinvite_service": { 37 | "other_platform_oauth_client": [ 38 | { 39 | "client_id": "605509048106-v1u5udkhv45cq0unvd7ckuqqeei8fpet.apps.googleusercontent.com", 40 | "client_type": 3 41 | } 42 | ] 43 | } 44 | } 45 | } 46 | ], 47 | "configuration_version": "1" 48 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/app/App.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.app; 2 | 3 | import android.app.Application; 4 | 5 | public class App extends Application { 6 | 7 | private static App instance; 8 | 9 | public static App getInstance() { 10 | return instance; 11 | } 12 | 13 | @Override 14 | public void onCreate() { 15 | super.onCreate(); 16 | instance = this; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/app/AppActivity.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.app; 2 | 3 | import android.widget.Toast; 4 | 5 | import androidx.annotation.NonNull; 6 | import androidx.annotation.StringRes; 7 | import androidx.appcompat.app.AppCompatActivity; 8 | 9 | public abstract class AppActivity extends AppCompatActivity { 10 | 11 | protected final void showMessage(@NonNull String message) { 12 | Toast.makeText(this, message, Toast.LENGTH_LONG).show(); 13 | } 14 | 15 | protected final void showMessage(@StringRes int res) { 16 | showMessage(getString(res)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/data/DBConstants.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.data; 2 | 3 | public class DBConstants { 4 | 5 | public static final String DB_LOCATION = "/data/data/com.sample.google.drive/databases/" + DBConstants.DB_NAME; 6 | 7 | static final String DB_NAME = "GoogleDriveSampleBd"; 8 | static final int DB_VERSION = 1; 9 | 10 | static final String TABLE_INFO = "TABLE_INFO"; 11 | static final String INFO_FIELD_TEXT = "INFO_FIELD_TEXT"; 12 | 13 | static final String DATABASE_CREATE; 14 | static { 15 | DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " 16 | + TABLE_INFO 17 | + " (" + INFO_FIELD_TEXT + " VARCHAR);"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/data/DatabaseOpenHelper.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.data; 2 | 3 | import com.sample.google.drive.app.App; 4 | 5 | import android.content.Context; 6 | import android.database.sqlite.SQLiteDatabase; 7 | import android.database.sqlite.SQLiteOpenHelper; 8 | 9 | import static com.sample.google.drive.data.DBConstants.*; 10 | 11 | class DatabaseOpenHelper extends SQLiteOpenHelper { 12 | 13 | static SQLiteDatabase getAppDatabase() { 14 | final DatabaseOpenHelper helper = new DatabaseOpenHelper(App.getInstance()); 15 | return helper.getWritableDatabase(); 16 | } 17 | 18 | private DatabaseOpenHelper(Context context) { 19 | super(context, DB_NAME, null, DB_VERSION); 20 | } 21 | 22 | @Override 23 | public void onCreate(SQLiteDatabase database) { 24 | database.execSQL(DATABASE_CREATE); 25 | } 26 | 27 | @Override 28 | public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { 29 | onCreate(database); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/data/InfoRepository.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.data; 2 | 3 | import android.content.ContentValues; 4 | import android.database.Cursor; 5 | import android.database.sqlite.SQLiteDatabase; 6 | 7 | import androidx.annotation.NonNull; 8 | import androidx.annotation.Nullable; 9 | 10 | public class InfoRepository { 11 | 12 | private final SQLiteDatabase db = DatabaseOpenHelper.getAppDatabase(); 13 | 14 | public void writeInfo(@NonNull String info) { 15 | ContentValues values = new ContentValues(); 16 | values.put(DBConstants.INFO_FIELD_TEXT, info); 17 | db.insert(DBConstants.TABLE_INFO, null, values); 18 | db.close(); 19 | } 20 | 21 | @Nullable 22 | public String getInfo() { 23 | String info; 24 | final String[] cols = new String[]{DBConstants.INFO_FIELD_TEXT}; 25 | try (Cursor cursor = db.query( 26 | true, 27 | DBConstants.TABLE_INFO, 28 | cols, 29 | null, 30 | null, 31 | null, 32 | null, 33 | null, 34 | null)) { 35 | cursor.moveToLast(); 36 | info = cursor.getString(0); 37 | } 38 | return info; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/google/GoogleDriveActivity.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.google; 2 | 3 | import com.google.android.gms.auth.api.signin.GoogleSignInAccount; 4 | import com.google.android.gms.auth.api.signin.GoogleSignInOptions; 5 | import com.google.android.gms.common.Scopes; 6 | import com.google.android.gms.common.api.ApiException; 7 | import com.google.android.gms.common.api.Scope; 8 | import com.google.api.client.extensions.android.http.AndroidHttp; 9 | import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; 10 | import com.google.api.client.json.gson.GsonFactory; 11 | import com.google.api.services.drive.Drive; 12 | import com.google.api.services.drive.DriveScopes; 13 | import com.sample.google.drive.R; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | public abstract class GoogleDriveActivity extends GoogleSignInActivity { 19 | 20 | protected void startGoogleDriveSignIn() { 21 | startGoogleSignIn(); 22 | } 23 | 24 | protected abstract void onGoogleDriveSignedInSuccess(final Drive driveApi); 25 | 26 | protected abstract void onGoogleDriveSignedInFailed(final ApiException exception); 27 | 28 | @Override 29 | protected GoogleSignInOptions getGoogleSignInOptions() { 30 | Scope scopeDriveAppFolder = new Scope(Scopes.DRIVE_APPFOLDER); 31 | return new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 32 | .requestEmail() 33 | .requestScopes(scopeDriveAppFolder) 34 | .build(); 35 | } 36 | 37 | @Override 38 | protected void onGoogleSignedInSuccess(final GoogleSignInAccount signInAccount) { 39 | initializeDriveClient(signInAccount); 40 | } 41 | 42 | @Override 43 | protected void onGoogleSignedInFailed(final ApiException exception) { 44 | onGoogleDriveSignedInFailed(exception); 45 | } 46 | 47 | private void initializeDriveClient(GoogleSignInAccount signInAccount) { 48 | List scopes = new ArrayList<>(); 49 | scopes.add(DriveScopes.DRIVE_APPDATA); 50 | 51 | GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, scopes); 52 | credential.setSelectedAccount(signInAccount.getAccount()); 53 | Drive.Builder builder = new Drive.Builder( 54 | AndroidHttp.newCompatibleTransport(), 55 | new GsonFactory(), 56 | credential 57 | ); 58 | String appName = getString(R.string.app_name); 59 | Drive driveApi = builder 60 | .setApplicationName(appName) 61 | .build(); 62 | onGoogleDriveSignedInSuccess(driveApi); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/google/GoogleDriveApiDataRepository.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.google; 2 | 3 | import android.util.Base64; 4 | 5 | import com.google.android.gms.tasks.Task; 6 | import com.google.android.gms.tasks.Tasks; 7 | import com.google.api.client.http.ByteArrayContent; 8 | import com.google.api.services.drive.Drive; 9 | import com.google.api.services.drive.model.File; 10 | import com.google.api.services.drive.model.FileList; 11 | import com.sample.google.drive.util.ByteSegments; 12 | import com.sample.google.drive.util.FileInputSource; 13 | 14 | import java.io.BufferedReader; 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.io.InputStreamReader; 19 | import java.util.Collections; 20 | import java.util.concurrent.Executor; 21 | import java.util.concurrent.Executors; 22 | 23 | import androidx.annotation.NonNull; 24 | 25 | public class GoogleDriveApiDataRepository { 26 | 27 | private final String FILE_MIME_TYPE = "text/plain"; 28 | private final String APP_DATA_FOLDER_SPACE = "appDataFolder"; 29 | 30 | private final Executor mExecutor = Executors.newSingleThreadExecutor(); 31 | 32 | private final Drive mDriveService; 33 | 34 | public GoogleDriveApiDataRepository(Drive driveApi) { 35 | this.mDriveService = driveApi; 36 | } 37 | 38 | public Task uploadFile(@NonNull final java.io.File file, @NonNull final String fileName) { 39 | return createFile(fileName) 40 | .continueWithTask(mExecutor, task -> { 41 | final String fileId = task.getResult(); 42 | if (fileId == null) { 43 | throw new IOException("Null file id when requesting file upload."); 44 | } 45 | return writeFile(file, fileId, fileName); 46 | }); 47 | } 48 | 49 | public Task downloadFile(@NonNull final java.io.File file, @NonNull final String fileName) { 50 | return queryFiles() 51 | .continueWithTask(mExecutor, task -> { 52 | final FileList fileList = task.getResult(); 53 | if (fileList == null) { 54 | throw new IOException("Null file list when requesting file download."); 55 | } 56 | File currentFile = null; 57 | for (File f : fileList.getFiles()) { 58 | if (f.getName().equals(fileName)) { 59 | currentFile = f; 60 | break; 61 | } 62 | } 63 | if (currentFile == null) { 64 | throw new IOException("File not found when requesting file download."); 65 | } 66 | 67 | final String fileId = currentFile.getId(); 68 | return readFile(file, fileId); 69 | }); 70 | } 71 | 72 | private Task readFile( 73 | @NonNull final java.io.File file, 74 | @NonNull final String fileId 75 | ) { 76 | return Tasks.call(mExecutor, () -> { 77 | String encoded; 78 | try (InputStream is = mDriveService.files().get(fileId).executeMediaAsInputStream(); 79 | BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { 80 | 81 | StringBuilder stringBuilder = new StringBuilder(); 82 | String line; 83 | 84 | while ((line = reader.readLine()) != null) { 85 | stringBuilder.append(line); 86 | } 87 | encoded = stringBuilder.toString(); 88 | } 89 | 90 | final byte[] decoded = Base64.decode(encoded, Base64.DEFAULT); 91 | try (FileOutputStream stream = new FileOutputStream(file)) { 92 | stream.write(decoded); 93 | } 94 | return null; 95 | }); 96 | } 97 | 98 | public Task queryFiles() { 99 | return Tasks.call(mExecutor, () -> mDriveService.files().list().setSpaces(APP_DATA_FOLDER_SPACE).execute()); 100 | } 101 | 102 | private Task writeFile( 103 | @NonNull final java.io.File file, 104 | @NonNull final String fileId, 105 | @NonNull final String fileName 106 | ) { 107 | return Tasks.call(mExecutor, () -> { 108 | File metadata = getMetaData(fileName); 109 | 110 | byte[] bytes = ByteSegments.toByteArray(new FileInputSource(file)); 111 | final String encoded = Base64.encodeToString(bytes, Base64.DEFAULT); 112 | ByteArrayContent contentStream = ByteArrayContent.fromString(FILE_MIME_TYPE, encoded); 113 | 114 | // Update the metadata and contents. 115 | mDriveService.files().update(fileId, metadata, contentStream).execute(); 116 | return null; 117 | }); 118 | } 119 | 120 | private Task createFile(@NonNull final String fileName) { 121 | return Tasks.call(mExecutor, () -> { 122 | File metadata = getMetaData(fileName); 123 | metadata.setParents(Collections.singletonList(APP_DATA_FOLDER_SPACE)); 124 | File googleFile = mDriveService.files().create(metadata).execute(); 125 | if (googleFile == null) { 126 | throw new IOException("Null result when requesting file creation."); 127 | } 128 | return googleFile.getId(); 129 | }); 130 | } 131 | 132 | private File getMetaData(@NonNull final String fileName) { 133 | return new File() 134 | .setMimeType(FILE_MIME_TYPE) 135 | .setName(fileName); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/google/GoogleSignInActivity.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.google; 2 | 3 | import android.content.Intent; 4 | 5 | import com.google.android.gms.auth.api.signin.GoogleSignIn; 6 | import com.google.android.gms.auth.api.signin.GoogleSignInAccount; 7 | import com.google.android.gms.auth.api.signin.GoogleSignInClient; 8 | import com.google.android.gms.auth.api.signin.GoogleSignInOptions; 9 | import com.google.android.gms.common.api.ApiException; 10 | import com.google.android.gms.tasks.Task; 11 | import com.sample.google.drive.app.AppActivity; 12 | 13 | public abstract class GoogleSignInActivity extends AppActivity { 14 | 15 | private static final int GOOGLE_SIGN_IN_REQUEST = 1010; 16 | 17 | protected abstract GoogleSignInOptions getGoogleSignInOptions(); 18 | 19 | protected abstract void onGoogleSignedInSuccess(final GoogleSignInAccount signInAccount); 20 | 21 | protected abstract void onGoogleSignedInFailed(final ApiException exception); 22 | 23 | protected void startGoogleSignIn() { 24 | GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, getGoogleSignInOptions()); 25 | Intent signInIntent = googleSignInClient.getSignInIntent(); 26 | startActivityForResult(signInIntent, GOOGLE_SIGN_IN_REQUEST); 27 | } 28 | 29 | @Override 30 | protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { 31 | super.onActivityResult(requestCode, resultCode, data); 32 | if (requestCode == GOOGLE_SIGN_IN_REQUEST) { 33 | Task task = GoogleSignIn.getSignedInAccountFromIntent(data); 34 | handleSignInResult(task); 35 | } 36 | } 37 | 38 | private void handleSignInResult(Task completedTask) { 39 | try { 40 | GoogleSignInAccount account = completedTask.getResult(ApiException.class); 41 | onGoogleSignedInSuccess(account); 42 | } catch (ApiException e) { 43 | onGoogleSignedInFailed(e); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/ui/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.ui; 2 | 3 | import android.os.Bundle; 4 | import android.util.Log; 5 | import android.view.View; 6 | import android.widget.Button; 7 | import android.widget.EditText; 8 | 9 | import com.google.android.gms.common.api.ApiException; 10 | import com.google.api.services.drive.Drive; 11 | import com.sample.google.drive.R; 12 | import com.sample.google.drive.data.DBConstants; 13 | import com.sample.google.drive.data.InfoRepository; 14 | import com.sample.google.drive.google.GoogleDriveActivity; 15 | import com.sample.google.drive.google.GoogleDriveApiDataRepository; 16 | 17 | import java.io.File; 18 | 19 | import androidx.constraintlayout.widget.Group; 20 | 21 | public class MainActivity extends GoogleDriveActivity { 22 | 23 | private static final String LOG_TAG = "MainActivity"; 24 | 25 | private static final String GOOGLE_DRIVE_DB_LOCATION = "db"; 26 | 27 | private Button googleSignIn; 28 | private Group contentViews; 29 | private EditText inputToDb; 30 | private Button writeToDb; 31 | private Button saveToGoogleDrive; 32 | private Button restoreFromDb; 33 | 34 | private GoogleDriveApiDataRepository repository; 35 | 36 | @Override 37 | protected void onCreate(Bundle savedInstanceState) { 38 | super.onCreate(savedInstanceState); 39 | setContentView(R.layout.activity_main); 40 | findViews(); 41 | initViews(); 42 | } 43 | 44 | @Override 45 | protected void onGoogleDriveSignedInSuccess(Drive driveApi) { 46 | showMessage(R.string.message_drive_client_is_ready); 47 | repository = new GoogleDriveApiDataRepository(driveApi); 48 | googleSignIn.setVisibility(View.GONE); 49 | contentViews.setVisibility(View.VISIBLE); 50 | } 51 | 52 | @Override 53 | protected void onGoogleDriveSignedInFailed(ApiException exception) { 54 | showMessage(R.string.message_google_sign_in_failed); 55 | Log.e(LOG_TAG, "error google drive sign in", exception); 56 | } 57 | 58 | private void findViews() { 59 | googleSignIn = findViewById(R.id.google_sign_in); 60 | contentViews = findViewById(R.id.content_views); 61 | inputToDb = findViewById(R.id.edit_text_db_input); 62 | writeToDb = findViewById(R.id.write_to_db); 63 | saveToGoogleDrive = findViewById(R.id.save_to_google_drive); 64 | restoreFromDb = findViewById(R.id.restore_from_db); 65 | } 66 | 67 | private void initViews() { 68 | googleSignIn.setOnClickListener(v -> { 69 | startGoogleDriveSignIn(); 70 | }); 71 | 72 | writeToDb.setOnClickListener(v -> { 73 | String text = inputToDb.getText().toString(); 74 | InfoRepository repository = new InfoRepository(); 75 | repository.writeInfo(text); 76 | }); 77 | 78 | saveToGoogleDrive.setOnClickListener(v -> { 79 | File db = new File(DBConstants.DB_LOCATION); 80 | if (repository == null) { 81 | showMessage(R.string.message_google_sign_in_failed); 82 | return; 83 | } 84 | 85 | repository.uploadFile(db, GOOGLE_DRIVE_DB_LOCATION) 86 | .addOnSuccessListener(r -> showMessage("Upload success")) 87 | .addOnFailureListener(e -> { 88 | Log.e(LOG_TAG, "error upload file", e); 89 | showMessage("Error upload"); 90 | }); 91 | }); 92 | 93 | restoreFromDb.setOnClickListener(v -> { 94 | if (repository == null) { 95 | showMessage(R.string.message_google_sign_in_failed); 96 | return; 97 | } 98 | 99 | File db = new File(DBConstants.DB_LOCATION); 100 | db.getParentFile().mkdirs(); 101 | db.delete(); 102 | repository.downloadFile(db, GOOGLE_DRIVE_DB_LOCATION) 103 | .addOnSuccessListener(r -> { 104 | InfoRepository repository = new InfoRepository(); 105 | String infoText = repository.getInfo(); 106 | inputToDb.setText(infoText); 107 | showMessage("Retrieved"); 108 | }) 109 | .addOnFailureListener(e -> { 110 | Log.e(LOG_TAG, "error download file", e); 111 | showMessage("Error download"); 112 | }); 113 | }); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/util/ByteSegments.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.util; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | 7 | import androidx.annotation.NonNull; 8 | 9 | public final class ByteSegments { 10 | 11 | private Segment head; 12 | 13 | public static byte[] toByteArray(InputStream is) throws IOException { 14 | return new ByteSegments() 15 | .readFrom(is) 16 | .toByteArray(); 17 | } 18 | 19 | public static byte[] toByteArray(InputSource source) throws IOException { 20 | InputStream is = source.open(); 21 | try { 22 | return toByteArray(is); 23 | } finally { 24 | IOUtils.close(is); 25 | } 26 | } 27 | 28 | public int size() { 29 | return head != null ? head.prevSize + head.pos : 0; 30 | } 31 | 32 | public int allocatedSize() { 33 | return head != null ? head.count * Segment.SIZE : 0; 34 | } 35 | 36 | public byte[] toByteArray() { 37 | byte[] array = new byte[size()]; 38 | Segment it = head; 39 | while (it != null) { 40 | System.arraycopy(it.data, 0, array, it.prevSize, it.pos); 41 | it = it.prev; 42 | } 43 | return array; 44 | } 45 | 46 | public ByteSegments readFrom(InputStream is) throws IOException { 47 | int read; 48 | while (true) { 49 | Segment segment = current(); 50 | read = is.read(segment.data, segment.pos, segment.availLength()); 51 | if (read == -1) { 52 | return this; 53 | } 54 | segment.pos += read; 55 | } 56 | } 57 | 58 | public OutputStream outputStream() { 59 | return new OutputStream() { 60 | @Override 61 | public void write(int b) throws IOException { 62 | write(new byte[]{(byte) b}); 63 | } 64 | 65 | @Override 66 | public void write(@NonNull byte[] buffer) throws IOException { 67 | write(buffer, 0, buffer.length); 68 | } 69 | 70 | @Override 71 | public void write(@NonNull byte[] buffer, int offset, int length) throws IOException { 72 | while (length > 0) { 73 | Segment segment = current(); 74 | int copy = Math.min(segment.availLength(), length); 75 | System.arraycopy(buffer, offset, segment.data, segment.pos, copy); 76 | segment.pos += copy; 77 | offset += copy; 78 | length -= copy; 79 | } 80 | } 81 | }; 82 | } 83 | 84 | public InputStream inputStream() { 85 | return new InputStream() { 86 | private int position = 0; 87 | private int mark; 88 | 89 | @Override 90 | public int read() throws IOException { 91 | Segment it = head; 92 | while (it != null) { 93 | int pos = position - it.prevSize; 94 | if (0 <= pos && pos < it.pos) { 95 | ++position; 96 | return it.data[pos]; 97 | } 98 | it = it.prev; 99 | } 100 | return -1; 101 | } 102 | 103 | @Override 104 | public int read(@NonNull byte[] buffer) throws IOException { 105 | return read(buffer, 0, buffer.length); 106 | } 107 | 108 | @Override 109 | public int read(@NonNull byte[] buffer, int offset, int length) throws IOException { 110 | int position = this.position; 111 | if (position >= size()) { 112 | return -1; 113 | } 114 | Segment it = head; 115 | while (it != null) { 116 | int index = position - it.prevSize; 117 | int start = Math.max(0, Math.min(it.pos, index)); 118 | int end = Math.max(0, Math.min(it.pos, index + length)); 119 | int copy = end - start; 120 | if (copy != 0) { 121 | int target = offset + start - index; 122 | System.arraycopy(it.data, start, buffer, target, copy); 123 | } 124 | it = it.prev; 125 | } 126 | this.position = Math.min(size(), position + length); 127 | return this.position - position; 128 | } 129 | 130 | @Override 131 | public long skip(long l) throws IOException { 132 | int oldPosition = position; 133 | position = Math.min(size(), position + (int) l); 134 | return position - oldPosition; 135 | } 136 | 137 | @Override 138 | public int available() throws IOException { 139 | return size() - position; 140 | } 141 | 142 | @Override 143 | public void mark(int i) { 144 | mark = position; 145 | } 146 | 147 | @Override 148 | public void reset() { 149 | position = mark; 150 | } 151 | 152 | @Override 153 | public boolean markSupported() { 154 | return true; 155 | } 156 | }; 157 | } 158 | 159 | public void copyTo(OutputStream outputStream) throws IOException { 160 | if (head != null) { 161 | head.writeTo(outputStream); 162 | } 163 | } 164 | 165 | private Segment current() { 166 | Segment segment = head; 167 | if (segment == null || segment.pos == Segment.SIZE) { 168 | return next(); 169 | } 170 | return segment; 171 | } 172 | 173 | private Segment next() { 174 | return head = new Segment(head); 175 | } 176 | 177 | private static class Segment { 178 | static final int SIZE = 4096; 179 | 180 | final byte[] data = new byte[SIZE]; 181 | 182 | final Segment prev; 183 | final int prevSize; 184 | final int count; 185 | 186 | int pos; 187 | 188 | Segment(Segment prev) { 189 | this.prev = prev; 190 | prevSize = prev == null ? 0 : prev.prevSize + prev.pos; 191 | count = prev == null ? 1 : prev.count + 1; 192 | } 193 | 194 | int availLength() { 195 | return SIZE - pos; 196 | } 197 | 198 | void writeTo(OutputStream outputStream) throws IOException { 199 | if (prev != null) { 200 | prev.writeTo(outputStream); 201 | } 202 | outputStream.write(data, 0, pos); 203 | } 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/util/FileInputSource.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.util; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.InputStream; 7 | 8 | public final class FileInputSource implements InputSource { 9 | 10 | private final File file; 11 | 12 | public FileInputSource(File file) { 13 | this.file = file; 14 | } 15 | 16 | @Override 17 | public InputStream open() throws FileNotFoundException { 18 | return new FileInputStream(file); 19 | } 20 | 21 | @Override 22 | public long length() { 23 | return file.length(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/util/IOUtils.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.util; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | 7 | import androidx.annotation.Nullable; 8 | 9 | public final class IOUtils { 10 | 11 | public static void skip(InputStream is, long n) throws IOException { 12 | while (n > 0) { 13 | long skipped = is.skip(n); 14 | if (skipped > 0) { 15 | n -= skipped; 16 | } else if (skipped == 0) { 17 | if (is.read() == -1) { 18 | break; 19 | } else { 20 | --n; 21 | } 22 | } 23 | } 24 | } 25 | 26 | public static void close(@Nullable Closeable closeable) { 27 | if (closeable != null) { 28 | try { 29 | closeable.close(); 30 | } catch (Exception ignored) { 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /app/src/main/java/com/sample/google/drive/util/InputSource.java: -------------------------------------------------------------------------------- 1 | package com.sample.google.drive.util; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.InputStream; 5 | 6 | public interface InputSource { 7 | InputStream open() throws FileNotFoundException; 8 | 9 | long length(); 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 |