├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── drivebackupsample │ │ ├── DriveExtensions.kt │ │ ├── DriveUploadWorker.kt │ │ ├── DriveUploadWorkerFactory.kt │ │ ├── FileViewModel.kt │ │ ├── MainActivity.kt │ │ └── MyApplication.kt │ └── 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 ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | *.aab 5 | 6 | # Files for the ART/Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | out/ 16 | release/ 17 | 18 | # Gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | 25 | # Proguard folder generated by Eclipse 26 | proguard/ 27 | 28 | # Log Files 29 | *.log 30 | 31 | # Android Studio Navigation editor temp files 32 | .navigation/ 33 | 34 | # Android Studio captures folder 35 | captures/ 36 | 37 | # IntelliJ 38 | *.iml 39 | .idea/ 40 | 41 | # Keystore files 42 | # Uncomment the following lines if you do not want to check your keystore files in. 43 | #*.jks 44 | #*.keystore 45 | 46 | # External native build folder generated in Android Studio 2.2 and later 47 | .externalNativeBuild 48 | 49 | # Google Services (e.g. APIs or Firebase) 50 | # google-services.json 51 | 52 | # Freeline 53 | freeline.py 54 | freeline/ 55 | freeline_project_description.json 56 | 57 | # fastlane 58 | fastlane/report.xml 59 | fastlane/Preview.html 60 | fastlane/screenshots 61 | fastlane/test_output 62 | fastlane/readme.md 63 | 64 | # Version control 65 | vcs.xml 66 | 67 | # lint 68 | lint/intermediates/ 69 | lint/generated/ 70 | lint/outputs/ 71 | lint/tmp/ 72 | # lint/reports/ 73 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows 28 | [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright [yyyy] [name of copyright owner] 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android on Chrome OS & Google Drive Android API Sample 2 | 3 | This application serves as an example of how to use the Google Drive API to 4 | pull down your app's files as well as update them in the background using 5 | [Work Manager API's.](https://developer.android.com/topic/libraries/architecture/workmanager) 6 | 7 | This serves as a starting point to allow you to easily store data in Drive 8 | while being able to recover the files if the profile on the Chrome OS Device is 9 | deleted or removed due to lack of memory. 10 | 11 | ## What does it do? 12 | 13 | * Creates text files in the user's My Drive folder 14 | * Edits file contents and metadata and saves them to Drive 15 | * Queries the REST API for all files visible to the app using the [Drive 16 | Client Library.](https://developers.google.com/drive/api/v3/about-sdk) 17 | * Updates/Creates text files in the background using Work Manager 18 | 19 | ## Getting started with the sample 20 | * `Main Activity` handles the authorization of the user and the creation of the 21 | Google Drive service with this authorization. 22 | * `FileViewModel` handles most of the conversation between the buttons in the 23 | activity and making the calls to the Drive API. This is also the launch of 24 | the coroutines where we are making these calls. 25 | * `DriveExtensions.kt` enhances the Drive API to handle network calls. 26 | * The remaining class enable background processing with WorkManager. We are 27 | using a `DelegatingWorkFactory` to be ableto create our workers with the 28 | API client that we need. 29 | 30 | ## Things to keep in mind? 31 | * Using WorkManager to save things in the background is great, but there are 32 | many ways that the user could stop this from occurring. On Chrome OS, logging out 33 | of the device or closing the lid will turn off the Android container and in turn 34 | will stop anything running in the background. 35 | 36 | As a disclaimer: this sample handles this by pushing to the background if you 37 | choose to use that option, and it will be stopped if the Android container is 38 | stopped 39 | * One other thing to note is that we are not setting any constraints 40 | on our Work Manager jobs, due to this being a Chrome OS based sample, the same 41 | network and battery constraints don't necessarily apply the same due to Chrome 42 | OS devices having larger batteries and not LTE enabled. Take note of this if you 43 | are also building apps for both Chrome OS devices and phones. 44 | 45 | ## Set Up (Mostly Drive API setup) 46 | 47 | 1. Install the [Android SDK](https://developer.android.com/sdk/index.html). 48 | 2. Download and configure the 49 | [Google Play services SDK](https://developer.android.com/google/play-services/setup.html). 50 | 3. Create a 51 | [Google API Console](https://console.developers.google.com/projectselector/apis/dashboard) 52 | project and enable the Drive API library. 53 | 4. Register an OAuth 2.0 client for the package 54 | `com.google.android.gms.drive.sample.driveapimigration` with your own 55 | [debug keys](https://developers.google.com/drive/android/auth). 56 | 5. Add the `../auth/drive.file` scope to the OAuth consent screen in the API 57 | Console. 58 | 59 | See full instructions in the 60 | [Getting Started guide](https://developers.google.com/drive/android/get-started). 61 | 62 | Find [API Documentation and references here](https://developers.google.com/drive/api/v3/about-sdk) 63 | 64 | Support 65 | ------- 66 | 67 | If you've found an error in this sample, please 68 | [file an issue](https://github.com/chromeos/android-google-drive-backup-sample/issues) 69 | 70 | Patches are encouraged, and may be submitted by forking this project and 71 | submitting a pull request through GitHub. Please see 72 | [CONTRIBUTING.md](CONTRIBUTING.md) for more details. 73 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | 19 | apply plugin: 'kotlin-android' 20 | 21 | apply plugin: 'kotlin-android-extensions' 22 | 23 | android { 24 | compileSdkVersion 29 25 | defaultConfig { 26 | applicationId "com.example.drivebackupsample" 27 | minSdkVersion 21 28 | targetSdkVersion 29 29 | versionCode 1 30 | versionName "1.0" 31 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 32 | } 33 | buildTypes { 34 | release { 35 | minifyEnabled true 36 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 37 | } 38 | } 39 | compileOptions { 40 | sourceCompatibility JavaVersion.VERSION_1_8 41 | targetCompatibility JavaVersion.VERSION_1_8 42 | } 43 | 44 | kotlinOptions { 45 | jvmTarget = JavaVersion.VERSION_1_8 46 | } 47 | 48 | packagingOptions { 49 | exclude 'META-INF/DEPENDENCIES' 50 | exclude 'META-INF/LICENSE' 51 | exclude 'META-INF/LICENSE.txt' 52 | exclude 'META-INF/license.txt' 53 | exclude 'META-INF/NOTICE' 54 | exclude 'META-INF/NOTICE.txt' 55 | exclude 'META-INF/notice.txt' 56 | exclude 'META-INF/ASL2.0' 57 | } 58 | } 59 | 60 | dependencies { 61 | implementation fileTree(dir: 'libs', include: ['*.jar']) 62 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 63 | 64 | implementation 'androidx.appcompat:appcompat:1.1.0' 65 | implementation 'androidx.core:core-ktx:1.1.0' 66 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 67 | implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha05' 68 | implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha05' 69 | implementation ('androidx.work:work-runtime-ktx:2.2.0'){ 70 | //Needed due to a transitive dependency clash with the google api client dep 71 | exclude group: 'com.google.guava', module:'listenablefuture' 72 | } 73 | 74 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0' 75 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0' 76 | 77 | implementation 'com.google.android.gms:play-services-auth:17.0.0' 78 | implementation 'com.google.http-client:google-http-client-gson:1.26.0' 79 | implementation 'com.google.api-client:google-api-client-android:1.26.0' 80 | implementation 'com.google.apis:google-api-services-drive:v3-rev136-1.25.0' 81 | 82 | testImplementation 'junit:junit:4.12' 83 | androidTestImplementation 'androidx.test.ext:junit:1.1.0' 84 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 85 | } 86 | -------------------------------------------------------------------------------- /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 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 25 | 33 | 34 | 35 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/drivebackupsample/DriveExtensions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.drivebackupsample 18 | 19 | import com.google.api.client.http.ByteArrayContent 20 | import com.google.api.services.drive.Drive 21 | import com.google.api.services.drive.DriveRequest 22 | import com.google.api.services.drive.model.File 23 | import com.google.api.services.drive.model.FileList 24 | import kotlinx.coroutines.Dispatchers 25 | import kotlinx.coroutines.withContext 26 | import org.apache.http.Consts 27 | import org.apache.http.entity.ContentType 28 | 29 | suspend fun DriveRequest.executeWithCoroutines(): T { 30 | return withContext(Dispatchers.IO) { 31 | execute() 32 | } 33 | } 34 | 35 | /** 36 | * Calls the Drive API to see if your app has a folder already, and if not creates one. 37 | * 38 | * @return the fetched folderId if existed or the newly created folderId 39 | */ 40 | suspend fun Drive.fetchOrCreateAppFolder(folderName: String): String { 41 | val folderList = getAppFolder() 42 | 43 | return if (folderList.files.isEmpty()) { 44 | val fileMetadata = File().apply { 45 | name = folderName 46 | mimeType = DriveContentType.DRIVE_FOLDER.mimeType 47 | } 48 | files().create(fileMetadata) 49 | .setFields("id") 50 | .executeWithCoroutines() 51 | .id 52 | } else { 53 | folderList.getFirst().id 54 | } 55 | } 56 | 57 | /** 58 | * Creates a text file in the user's Drive, in the application's folder and returns its file ID. 59 | * Mime type is text files only for this sample, change for your use case 60 | * 61 | * @return newly created fileId 62 | */ 63 | suspend fun Drive.createFile(folderId: String, fileName: String): String { 64 | val metadata = File().apply { 65 | parents = listOf(folderId) 66 | mimeType = ContentType.TEXT_PLAIN.mimeType 67 | name = fileName 68 | } 69 | return files() 70 | .create(metadata) 71 | .executeWithCoroutines() 72 | .id 73 | } 74 | 75 | /** 76 | * Opens the file identified by the given [fileId] and returns a [Pair] of its name and contents. 77 | */ 78 | suspend fun Drive.readFile(fileId: String): Pair { 79 | // Retrieve the metadata as a File object. 80 | val metadata = files().get(fileId).execute() 81 | val name = metadata.name 82 | 83 | // Stream the file contents to a String. 84 | return withContext(Dispatchers.IO) { 85 | val content = files().get(fileId).executeMediaAsInputStream() 86 | ?.bufferedReader() 87 | ?.use { it.readText() } 88 | ?: "" 89 | name to content 90 | } 91 | } 92 | 93 | /** 94 | * Updates the file identified by [fileId] with the given [name] and [content]. 95 | */ 96 | suspend fun Drive.saveFile(fileId: String, name: String, content: String) { 97 | // Create a File containing any metadata changes. 98 | val metadata = File().setName(name) 99 | 100 | val contentStream = ByteArrayContent.fromString(ContentType.TEXT_PLAIN.mimeType, content) 101 | 102 | // Update the metadata and contents. 103 | files().update(fileId, metadata, contentStream).executeWithCoroutines() 104 | } 105 | 106 | /** 107 | * Returns a [FileList] containing all the visible files in the user's My Drive. 108 | * 109 | * The returned list will only contain files visible to this app, i.e. those which were 110 | * created by this app. 111 | */ 112 | suspend fun Drive.getAllFiles(): FileList { 113 | return files().list().setSpaces("drive").executeWithCoroutines() 114 | } 115 | 116 | /** 117 | * Returns a [FileList] containing the folder associated with the app. 118 | * 119 | * The returned list will only contain folders created by the app, which in best practice should 120 | * only be 1 unless you need nested folders. 121 | */ 122 | suspend fun Drive.getAppFolder(): FileList { 123 | return files().list() 124 | .setSpaces("drive") 125 | .setQ("mimeType = '${DriveContentType.DRIVE_FOLDER.mimeType}'")//Special Drive folder mimeType 126 | .executeWithCoroutines() 127 | } 128 | 129 | fun FileList.getFirst(): File = files[0] 130 | 131 | object DriveContentType { 132 | val DRIVE_FOLDER = ContentType.create( 133 | "application/vnd.google-apps.folder", 134 | Consts.ISO_8859_1 135 | ) 136 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/drivebackupsample/DriveUploadWorker.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.drivebackupsample 18 | 19 | import android.content.Context 20 | import androidx.work.CoroutineWorker 21 | import androidx.work.WorkerParameters 22 | import com.google.api.services.drive.Drive 23 | import kotlinx.coroutines.coroutineScope 24 | 25 | class DriveUploadWorker( 26 | appContext: Context, 27 | workerParams: WorkerParameters, 28 | private val driveService: Drive 29 | ) : CoroutineWorker(appContext, workerParams) { 30 | 31 | override suspend fun doWork(): Result { 32 | val fileName = inputData.getString(KEY_NAME_ARG)!! 33 | val contents = inputData.getString(KEY_CONTENTS_ARG)!! 34 | val folderId = inputData.getString(KEY_CONTENTS_FOLDER_ID)!! 35 | return coroutineScope { 36 | val fileId = driveService.createFile(folderId, fileName) 37 | driveService.saveFile(fileId, fileName, contents) 38 | Result.success() 39 | } 40 | } 41 | 42 | companion object { 43 | const val KEY_NAME_ARG = "name" 44 | const val KEY_CONTENTS_ARG = "contents" 45 | const val KEY_CONTENTS_FOLDER_ID = "folder_id" 46 | } 47 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/drivebackupsample/DriveUploadWorkerFactory.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.drivebackupsample 18 | 19 | import android.content.Context 20 | import androidx.work.ListenableWorker 21 | import androidx.work.WorkerFactory 22 | import androidx.work.WorkerParameters 23 | import com.google.api.services.drive.Drive 24 | 25 | class DriveUploadWorkerFactory( 26 | private val driveService: Drive 27 | ) : WorkerFactory() { 28 | 29 | override fun createWorker( 30 | appContext: Context, 31 | workerClassName: String, 32 | workerParameters: WorkerParameters 33 | ): ListenableWorker? { 34 | 35 | return when (workerClassName) { 36 | DriveUploadWorker::class.java.name -> 37 | DriveUploadWorker(appContext, workerParameters, driveService) 38 | else -> 39 | // Return null, so that the base class can delegate to the default WorkerFactory. 40 | null 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/drivebackupsample/FileViewModel.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.drivebackupsample 18 | 19 | import android.app.Application 20 | import android.content.ContentResolver 21 | import android.content.Intent 22 | import android.net.Uri 23 | import android.provider.OpenableColumns 24 | import androidx.lifecycle.AndroidViewModel 25 | import androidx.lifecycle.LiveData 26 | import androidx.lifecycle.MutableLiveData 27 | import androidx.lifecycle.viewModelScope 28 | import androidx.work.OneTimeWorkRequestBuilder 29 | import androidx.work.WorkManager 30 | import androidx.work.workDataOf 31 | import com.google.api.services.drive.Drive 32 | import kotlinx.coroutines.Dispatchers 33 | import kotlinx.coroutines.launch 34 | import kotlinx.coroutines.withContext 35 | import java.io.IOException 36 | 37 | 38 | class FileViewModel(application: Application) : AndroidViewModel(application) { 39 | 40 | private val _numberOfFilesOwned: MutableLiveData = MutableLiveData() 41 | 42 | val numberOfFilesOwned: LiveData 43 | get() = _numberOfFilesOwned 44 | 45 | private lateinit var driveService: Drive 46 | private lateinit var appFolderId: String 47 | 48 | fun initializeDriveService(googleDriveServiceSession: Drive) { 49 | viewModelScope.launch { 50 | driveService = googleDriveServiceSession 51 | appFolderId = googleDriveServiceSession 52 | .fetchOrCreateAppFolder( 53 | getApplication().getString(R.string.application_folder) 54 | ) 55 | getApplication().initializeWorkManager(googleDriveServiceSession) 56 | } 57 | } 58 | 59 | fun getNumberOfFilesOwnedByApp() { 60 | viewModelScope.launch { 61 | val fileList = driveService.getAllFiles().files 62 | _numberOfFilesOwned.value = fileList.size 63 | } 64 | } 65 | 66 | private fun createFile(name: String = "Untitled File", contents: String = "default text") { 67 | viewModelScope.launch { 68 | val fileId = driveService.createFile(appFolderId, name) 69 | driveService.saveFile(fileId, name, contents) 70 | } 71 | } 72 | 73 | private fun createFileInBackground( 74 | name: String, 75 | contents: String = "default text" 76 | ) { 77 | val data = workDataOf( 78 | DriveUploadWorker.KEY_NAME_ARG to name, 79 | DriveUploadWorker.KEY_CONTENTS_ARG to contents, 80 | DriveUploadWorker.KEY_CONTENTS_FOLDER_ID to appFolderId 81 | ) 82 | 83 | val driveWorker = OneTimeWorkRequestBuilder() 84 | .setInputData(data) 85 | .build() 86 | WorkManager.getInstance(getApplication()).enqueue(driveWorker) 87 | } 88 | 89 | fun uploadFileFromAccessFramework( 90 | contentResolver: ContentResolver, 91 | uri: Uri, 92 | background: Boolean 93 | ) { 94 | viewModelScope.launch { 95 | val fileInformation = withContext(Dispatchers.IO) { 96 | openFileUsingStorageAccessFramework(contentResolver, uri) 97 | } 98 | if (!background) { 99 | createFile(fileInformation.first, fileInformation.second) 100 | } else { 101 | createFileInBackground(fileInformation.first, fileInformation.second) 102 | } 103 | } 104 | } 105 | 106 | companion object { 107 | /** 108 | * Opens the file at the [uri] returned by a Storage Access Framework [Intent] 109 | * using the given [contentResolver]. 110 | */ 111 | fun openFileUsingStorageAccessFramework( 112 | contentResolver: ContentResolver, 113 | uri: Uri 114 | ): Pair { 115 | // Retrieve the document's display name from its metadata. 116 | var name = "" 117 | contentResolver.query(uri, null, null, null, null)?.use { cursor -> 118 | if (cursor.moveToFirst()) { 119 | val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) 120 | name = cursor.getString(nameIndex) 121 | } else { 122 | throw IOException("Empty cursor returned for file.") 123 | } 124 | } 125 | 126 | // Read the document's contents as a String. 127 | val content = contentResolver.openInputStream(uri) 128 | ?.bufferedReader() 129 | ?.use { it.readText() } 130 | ?: "" 131 | 132 | return name to content 133 | } 134 | } 135 | 136 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/drivebackupsample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.drivebackupsample 18 | 19 | import androidx.appcompat.app.AppCompatActivity 20 | import android.os.Bundle 21 | import android.util.Log 22 | import com.google.android.gms.auth.api.signin.GoogleSignIn 23 | import com.google.android.gms.auth.api.signin.GoogleSignInOptions 24 | import com.google.android.gms.common.api.Scope 25 | import com.google.api.services.drive.DriveScopes 26 | import android.app.Activity 27 | import android.content.Intent 28 | import android.widget.Button 29 | import android.widget.TextView 30 | import androidx.lifecycle.Observer 31 | import androidx.lifecycle.ViewModelProvider 32 | import com.google.api.client.json.gson.GsonFactory 33 | import com.google.api.client.extensions.android.http.AndroidHttp 34 | import com.google.api.services.drive.Drive 35 | import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential 36 | import org.apache.http.entity.ContentType 37 | 38 | class MainActivity : AppCompatActivity() { 39 | 40 | private lateinit var uploadFileButton: Button 41 | private lateinit var uploadFileBackgroundButton: Button 42 | private lateinit var queryFilesButton: Button 43 | private lateinit var fileViewModel: FileViewModel 44 | private lateinit var numberOfFilesTextView: TextView 45 | 46 | /** 47 | * Creates an [Intent] for opening the Storage Access Framework file picker. 48 | */ 49 | private val filePickerIntent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { 50 | addCategory(Intent.CATEGORY_OPENABLE) 51 | type = ContentType.TEXT_PLAIN.mimeType 52 | } 53 | 54 | override fun onCreate(savedInstanceState: Bundle?) { 55 | super.onCreate(savedInstanceState) 56 | fileViewModel = ViewModelProvider(this)[FileViewModel::class.java] 57 | requestSignIn() 58 | 59 | setContentView(R.layout.activity_main) 60 | 61 | initializeUIElements() 62 | } 63 | 64 | public override fun onActivityResult( 65 | requestCode: Int, 66 | resultCode: Int, 67 | resultData: Intent? 68 | ) { 69 | if (resultData == null || resultCode != Activity.RESULT_OK) 70 | return super.onActivityResult(requestCode, resultCode, resultData) 71 | 72 | when (requestCode) { 73 | REQUEST_CODE_SIGN_IN -> handleSignInResult(resultData) 74 | REQUEST_CODE_OPEN_FILE -> resultData.data?.let { 75 | fileViewModel.uploadFileFromAccessFramework(contentResolver, it, false) 76 | } 77 | REQUEST_CODE_OPEN_FILE_BACKGROUND -> resultData.data?.let { 78 | fileViewModel.uploadFileFromAccessFramework(contentResolver, it, true) 79 | } 80 | } 81 | 82 | super.onActivityResult(requestCode, resultCode, resultData) 83 | } 84 | 85 | private fun requestSignIn() { 86 | val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 87 | .requestEmail() 88 | .requestScopes(Scope(DriveScopes.DRIVE_FILE), Scope(DriveScopes.DRIVE_APPDATA)) 89 | .build() 90 | val client = GoogleSignIn.getClient(this, signInOptions) 91 | 92 | // The result of the sign-in Intent is handled in onActivityResult. 93 | startActivityForResult(client.signInIntent, REQUEST_CODE_SIGN_IN) 94 | } 95 | 96 | private fun handleSignInResult(result: Intent) { 97 | GoogleSignIn.getSignedInAccountFromIntent(result) 98 | .addOnSuccessListener { googleAccount -> 99 | 100 | // Use the authenticated account to sign in to the Drive service. 101 | val credential = GoogleAccountCredential.usingOAuth2( 102 | this, 103 | listOf( 104 | DriveScopes.DRIVE_FILE, 105 | DriveScopes.DRIVE_APPDATA 106 | ) 107 | ) 108 | credential.selectedAccount = googleAccount.account 109 | val googleDriveService = Drive.Builder( 110 | AndroidHttp.newCompatibleTransport(), 111 | GsonFactory(), 112 | credential 113 | ).setApplicationName("Drive Backup Sample") 114 | .build() 115 | 116 | //Sets the drive api service on the view model and creates our apps folder 117 | fileViewModel.initializeDriveService(googleDriveService) 118 | } 119 | .addOnFailureListener { exception -> 120 | Log.e(TAG, "Unable to sign in.", exception) 121 | } 122 | } 123 | 124 | 125 | private fun initializeUIElements() { 126 | uploadFileButton = findViewById(R.id.upload_files_button) 127 | uploadFileBackgroundButton = findViewById(R.id.upload_files_background_button) 128 | queryFilesButton = findViewById(R.id.query_files_button) 129 | numberOfFilesTextView = findViewById(R.id.number_of_files_text_view) 130 | 131 | uploadFileButton.setOnClickListener { 132 | startActivityForResult(filePickerIntent, REQUEST_CODE_OPEN_FILE) 133 | } 134 | 135 | uploadFileBackgroundButton.setOnClickListener { 136 | startActivityForResult(filePickerIntent, REQUEST_CODE_OPEN_FILE_BACKGROUND) 137 | } 138 | queryFilesButton.setOnClickListener { 139 | fileViewModel.getNumberOfFilesOwnedByApp() 140 | } 141 | 142 | fileViewModel.numberOfFilesOwned.observe(this, Observer { numOfFiles -> 143 | val formattedString = getString(R.string.number_of_files, numOfFiles) 144 | numberOfFilesTextView.text = formattedString 145 | }) 146 | } 147 | 148 | companion object { 149 | private val TAG = MainActivity::class.java.simpleName 150 | private const val REQUEST_CODE_SIGN_IN = 1 151 | private const val REQUEST_CODE_OPEN_FILE = 2 152 | private const val REQUEST_CODE_OPEN_FILE_BACKGROUND = 3 153 | 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/drivebackupsample/MyApplication.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.drivebackupsample 18 | 19 | import android.app.Application 20 | import androidx.work.Configuration 21 | import androidx.work.DelegatingWorkerFactory 22 | import androidx.work.WorkManager 23 | import com.google.api.services.drive.Drive 24 | 25 | class MyApplication : Application(), Configuration.Provider { 26 | 27 | private val delegatingWorkerFactory = DelegatingWorkerFactory() 28 | 29 | override fun getWorkManagerConfiguration() = Configuration.Builder() 30 | .setMinimumLoggingLevel(android.util.Log.INFO) 31 | .setWorkerFactory(delegatingWorkerFactory) 32 | .build() 33 | 34 | fun initializeWorkManager(driveService: Drive): WorkManager { 35 | val factory = workManagerConfiguration.workerFactory as DelegatingWorkerFactory 36 | factory.addFactory(DriveUploadWorkerFactory(driveService)) 37 | 38 | return WorkManager.getInstance(this) 39 | } 40 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 23 | 28 | 29 | 35 | 38 | 41 | 42 | 43 | 44 | 50 | 51 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 22 | 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 | 175 | 180 | 185 | 186 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 23 | 24 |