├── .circleci └── config.yml ├── .github └── dependabot.yml ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── android-emulator-plugin ├── build.gradle ├── configuration │ ├── pmd.xml │ └── spotbugs-exclude.xml ├── gradle.properties └── src │ ├── main │ └── java │ │ └── com │ │ └── quittle │ │ └── androidemulator │ │ ├── AdbProxy.java │ │ ├── AndroidEmulatorExtension.java │ │ ├── AndroidEmulatorPlugin.java │ │ ├── AndroidRepositories.java │ │ ├── AndroidRepositoryException.java │ │ ├── ArchitectureUtils.java │ │ ├── CollectionUtils.java │ │ ├── EmulatorConfiguration.java │ │ ├── VersionComparator.java │ │ └── task │ │ ├── AddAdditionalSdkRepositoriesTask.java │ │ ├── AndroidEmulatorBaseExecTask.java │ │ ├── CreateEmulatorExecTask.java │ │ ├── EnsureBaseSdkPermissions.java │ │ ├── EnsureFilesAreExecutableTask.java │ │ ├── EnsureInstalledSdkPermissionsTask.java │ │ ├── InstallAndroidEmulatorSystemImageTask.java │ │ ├── InstallSdkDependenciesTask.java │ │ ├── ProcessDestroyer.java │ │ ├── StartAndroidEmulatorTask.java │ │ ├── StopAndroidEmulatorTask.java │ │ └── WaitForAndroidEmulatorTask.java │ └── test │ └── java │ └── com │ └── quittle │ └── androidemulator │ ├── ArchitectureUtilsTest.java │ ├── CollectionUtilsTest.java │ ├── EmulatorConfigurationTest.java │ └── VersionComparatorTest.java ├── example-android-project ├── build.gradle ├── gradle.properties └── src │ ├── androidTest │ └── java │ │ └── ExampleInstrumentationTest.java │ └── main │ └── AndroidManifest.xml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── validate_plugin /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | orbs: 3 | circleci-github-cli: circleci/github-cli@2.0.0 4 | workflows: 5 | Build and Test Workflow: 6 | jobs: 7 | - Build and Test: 8 | name: smoketest 9 | java: 8 10 | test_suite: 1 11 | filters: 12 | tags: 13 | only: /.*/ 14 | - Build and Test: 15 | requires: 16 | - smoketest 17 | java: 11 18 | matrix: 19 | parameters: 20 | test_suite: 21 | - 1 22 | - 2 23 | - 3 24 | - 5 25 | - 6 26 | - 7 27 | - 8 28 | - 9 29 | filters: 30 | tags: 31 | only: /.*/ 32 | - Deploy: 33 | requires: 34 | - Build and Test 35 | filters: 36 | tags: 37 | only: /^\d+\.\d+\.\d+$/ 38 | branches: 39 | ignore: /.*/ 40 | 41 | - Dependabot Auto-Merge: 42 | context: github-cli 43 | requires: 44 | - smoketest 45 | filters: 46 | branches: 47 | only: /dependabot\/.*/ 48 | 49 | jobs: 50 | Build and Test: 51 | description: Build and Test - JDK << parameters.java >> - Test Suite << parameters.test_suite >> 52 | parameters: 53 | java: 54 | type: integer 55 | test_suite: 56 | type: integer 57 | machine: 58 | image: android:2022.01.1 59 | resource_class: medium 60 | environment: 61 | GRADLE_OPTS: -Dorg.gradle.console=plain -Dorg.gradle.jvmargs=-XX:MaxMetaspaceSize=512m 62 | ADB_INSTALL_TIMEOUT: 3 63 | steps: 64 | - checkout 65 | - run: sudo apt-get update && sudo apt-get install openjdk-<< parameters.java >>-jdk 66 | - run: java -version 67 | - run: ./gradlew -p android-emulator-plugin 68 | - store_test_results: 69 | path: android-emulator-plugin/build/reports 70 | - run: ./validate_plugin << parameters.test_suite >> 71 | - store_test_results: 72 | path: example-android-project/build/reports 73 | Deploy: 74 | description: Deploy the plugin 75 | machine: 76 | image: android:2022.01.1 77 | environment: 78 | GRADLE_OPTS: -Dorg.gradle.console=plain -Dorg.gradle.jvmargs=-XX:MaxMetaspaceSize=512m 79 | steps: 80 | - checkout 81 | - run: sudo apt-get update && sudo apt-get install openjdk-8-jdk 82 | - run: java -version 83 | - run: ./gradlew -p android-emulator-plugin publishPlugins -Pgradle.publish.key=$GRADLE_PUBLISH_KEY -Pgradle.publish.secret=$GRADLE_PUBLISH_SECRET 84 | Dependabot Auto-Merge: 85 | docker: 86 | - image: cimg/base:2022.02 87 | steps: 88 | - checkout 89 | - circleci-github-cli/install 90 | - run: | 91 | PR_AUTHOR="$(gh pr view $CIRCLE_PULL_REQUEST --json author --jq .author.login)" 92 | if [ "$PR_AUTHOR" != "dependabot" ]; then 93 | message='Invalid PR author, rejecting'; 94 | echo "$message" 95 | gh pr review $CIRCLE_PULL_REQUEST --comment --body "$message" 96 | exit 1; 97 | else 98 | gh pr review $CIRCLE_PULL_REQUEST --comment --body "[Bot] Confirmed dependabot identity. @dependabot merge" 99 | gh pr review $CIRCLE_PULL_REQUEST --approve 100 | fi 101 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/android-emulator-plugin" 5 | schedule: 6 | interval: weekly 7 | day: friday 8 | time: "18:00" 9 | timezone: America/New_York 10 | reviewers: 11 | - quittle 12 | assignees: 13 | - quittle 14 | labels: 15 | - dependencies 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | local.properties 4 | android-emulator-plugin/bin/ 5 | *.class 6 | *.iml 7 | .idea/ 8 | */gradle* 9 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.configuration.updateBuildConfiguration": "automatic" 3 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Emulator Plugin [![Gradle Plugin Version](https://img.shields.io/maven-metadata/v/https/plugins.gradle.org/m2/com/quittle/android-emulator-plugin/maven-metadata.xml.svg?label=Gradle+Plugin+Version)](https://plugins.gradle.org/plugin/com.quittle.android-emulator) [![CircleCI](https://circleci.com/gh/quittle/gradle-android-emulator/tree/main.svg?style=svg)](https://circleci.com/gh/quittle/gradle-android-emulator/tree/main) 2 | 3 | This plugin adds tasks that install an Android emulator and start it up when running instrumentation tests. Includes configuration 4 | for specifying the emulator configuration. 5 | 6 | **This plugin will automatically accept all Android SDK licenses when installing the emulator and emulator 7 | system images. Before using the plugin or upgrading Android SDK versions, make sure you are okay accepting the 8 | licenses for those versions.** 9 | 10 | ## Consumption 11 | 12 | The minimum requirement for consumption is to simply 13 | [apply this plugin](https://plugins.gradle.org/plugin/com.quittle.android-emulator). 14 | 15 | #### build.gradle 16 | 17 | ```groovy 18 | // Consume from Gradle plugin repository. This is the only required step. 19 | plugins { 20 | id 'com.quittle.android-emulator' version 'X.X.X' 21 | } 22 | 23 | // Consume android plugin as usual. 24 | apply plugin: 'android' 25 | 26 | android { 27 | // Fill out normally 28 | } 29 | 30 | // Optional configuration 31 | androidEmulator { 32 | emulator { 33 | name 'my_avd_emulator_name' // Defaults to be dynamically based on the configuration of the AVD 34 | device 'pixel_xl' // Defaults to exclude the device flag, using avdmanager default. For options, run avdmanager list device 35 | sdkVersion 28 // Defaults to (Target SDK), then (Min SDK), then finally 10 36 | abi 'x86_64' // Defaults to x86 37 | includeGoogleApis true // Defaults to false 38 | } 39 | 40 | enableForAndroidTests false // Defaults to true 41 | avdRoot '~/.android/avd' // Defaults to be /android-avd-root 42 | headless true // Defaults to false but should be set to true for most CI systems 43 | additionalSdkManagerArguments '--proxy=http', '--proxy_host=56.78.90.12', '--proxy_port=1234' // Additional arguments to pass to the sdkmanager when used to install dependencies. See https://developer.android.com/studio/command-line/sdkmanager#options for options 44 | additionalEmulatorArguments '-no-snapshot', '-http-proxy=localhost:1234' // Additional arguments to pass to the emulator at startup. See https://developer.android.com/studio/run/emulator-commandline#startup-options for options 45 | logEmulatorOutput true // Defaults to false but can be enabled to have emulator output logged for debugging. 46 | } 47 | ``` 48 | 49 | ## Tips & Tricks 50 | 51 | ### Emulator failing to start 52 | 53 | If the emulator fails to start with an error like 54 | 55 | ``` 56 | Emulator exited abnormally with return code 1 57 | ``` 58 | 59 | and you are unsure what the cause is, set `androidEmulator { logEmulatorOutput true }` and re-run the 60 | gradle build or even just building the `waitForAndroidEmulator` with the `--debug` flag should do the 61 | trick. You should now see the emulator stdout and stderr being logged with error messages if there was 62 | a bad combination of startup flags. 63 | 64 | ### Custom test task 65 | 66 | If you have a reason to run a custom instrumentation test task rather than the default one generated by 67 | the Android Gradle plugin, you can certainly do so. All you must do to ensure the emulator is spun up 68 | and down at the appropriate times is 69 | 70 | 1. Configure your task to depend on `waitForAndroidEmulator` 71 | 2. Configure your task to be finalized by `stopAndroidEmulator` 72 | 73 | ## Development 74 | 75 | In general, perform builds in the context of each folder, rather than as a multi-project Gradle 76 | build. This is necessary because the `example-android-project` will fail to configure without the 77 | plugin being locally available so the `android-emulator-plugin` project must be built and deployed 78 | locally first. 79 | 80 | In general, to build and test locally do the following 81 | 82 | ``` 83 | $ ./gradlew -p android-emulator-plugin # This runs all the default tasks 84 | $ ./gradlew -p android-emulator-plugin publishToMavenLocal # Publishes it for the example-android-project to consume 85 | $ ./validate_plugin # Integration test to validate the plugin works 86 | ``` 87 | 88 | ## Deployment 89 | 90 | This package is deployed via [CircleCI](https://app.circleci.com/pipelines/github/quittle/gradle-android-emulator). 91 | See `.circleci/config.yml` for the CI/CD setup. 92 | 93 | In the configuration for the project on CircleCI, `GRADLE_PUBLISH_KEY` and `GRADLE_PUBLISH_SECRET` are 94 | injected as environment variables. 95 | 96 | Upon check-in to the `main` branch, CircleCI checks out and builds the plugin. When a commit is tagged, a new version of 97 | the plugin will be released using the tag version number. 98 | -------------------------------------------------------------------------------- /android-emulator-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | 6 | dependencies { 7 | classpath 'org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r' 8 | } 9 | } 10 | 11 | import com.github.spotbugs.snom.SpotBugsTask 12 | import org.eclipse.jgit.api.Git 13 | 14 | plugins { 15 | id 'com.github.spotbugs' version '5.0.14' 16 | id 'com.gradle.plugin-publish' version '1.2.0' 17 | id 'java-gradle-plugin' 18 | id 'maven-publish' 19 | id 'pmd' 20 | } 21 | 22 | repositories { 23 | google() 24 | mavenCentral() 25 | } 26 | 27 | group = 'com.quittle' 28 | version = Git.open(project.rootDir.parentFile) 29 | .describe() 30 | .setTarget("HEAD") 31 | .setTags(true) 32 | .call() 33 | 34 | gradlePlugin { 35 | plugins { 36 | androidEmulatorPlugin { 37 | id = 'com.quittle.android-emulator' 38 | implementationClass = 'com.quittle.androidemulator.AndroidEmulatorPlugin' 39 | displayName = 'Automated Android Emulator for easing development and testing' 40 | } 41 | } 42 | } 43 | 44 | publishing { 45 | publications { 46 | maven(MavenPublication) { 47 | artifactId = 'android-emulator' 48 | from components.java 49 | } 50 | } 51 | } 52 | 53 | pluginBundle { 54 | website = 'https://github.com/quittle/gradle-android-emulator' 55 | vcsUrl = 'https://github.com/quittle/gradle-android-emulator' 56 | description = 'Automatically installs and sets up the Android emulator for easy running of instrumentation tests.' 57 | tags = ['android', 'android emulator', 'emulator', 'automation', 'instrumentation'] 58 | } 59 | 60 | dependencies { 61 | compileOnly 'com.android.tools:common:31.0.2' 62 | def ANDROID_GRADLE_PLUGIN_VERSION = '8.0.2' 63 | compileOnly "com.android.tools.build:gradle:$ANDROID_GRADLE_PLUGIN_VERSION" 64 | implementation 'commons-io:commons-io:2.8.0' 65 | 66 | compileOnly 'com.google.code.findbugs:annotations:3.0.1' 67 | testCompileOnly 'com.google.code.findbugs:annotations:3.0.1' 68 | 69 | testImplementation 'io.mockk:mockk:1.13.5' 70 | testImplementation "com.android.tools.build:gradle:$ANDROID_GRADLE_PLUGIN_VERSION" 71 | testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0' 72 | testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.0' 73 | testImplementation 'org.mockito:mockito-junit-jupiter:5.4.0' 74 | } 75 | 76 | test { 77 | useJUnitPlatform() 78 | } 79 | 80 | tasks.withType(JavaCompile) { 81 | options.compilerArgs << '-Xlint:all' << '-Werror' << '-proc:none' 82 | } 83 | 84 | tasks.withType(SpotBugsTask) { 85 | reports { 86 | xml.enabled = false 87 | html.enabled = true 88 | } 89 | } 90 | 91 | javadoc { 92 | failOnError true 93 | options.addStringOption 'Xwerror', '-quiet' // See https://stackoverflow.com/a/49544352 94 | 95 | if (JavaVersion.current() != JavaVersion.VERSION_1_8) { 96 | options.addBooleanOption 'html5', true 97 | } 98 | } 99 | 100 | spotbugs { 101 | effort 'max' 102 | reportLevel 'low' 103 | excludeFilter = file('configuration/spotbugs-exclude.xml') 104 | } 105 | 106 | pmd { 107 | ruleSetFiles = files("configuration/pmd.xml") 108 | consoleOutput true 109 | ruleSets = [] 110 | } 111 | 112 | defaultTasks 'assemble', 'javadoc', 'check' 113 | -------------------------------------------------------------------------------- /android-emulator-plugin/configuration/pmd.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Custom 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /android-emulator-plugin/configuration/spotbugs-exclude.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android-emulator-plugin/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.warning.mode=all -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/AdbProxy.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import org.apache.commons.io.output.NullOutputStream; 4 | import org.gradle.api.GradleException; 5 | import org.gradle.api.Project; 6 | import org.gradle.process.ExecResult; 7 | 8 | import java.io.ByteArrayOutputStream; 9 | import java.nio.charset.StandardCharsets; 10 | import java.util.Arrays; 11 | 12 | /** 13 | * Provides a simplified abstraction of running ADB commands. 14 | */ 15 | public class AdbProxy { 16 | private final Project project; 17 | private final EmulatorConfiguration emulatorConfiguration; 18 | 19 | public AdbProxy(final Project project, final EmulatorConfiguration emulatorConfiguration) { 20 | this.project = project; 21 | this.emulatorConfiguration = emulatorConfiguration; 22 | } 23 | 24 | /** 25 | * Invokes {@code ADB} with the provided arguments, returning it's output. 26 | * @param arguments The arguments to pass to ADB. 27 | * @return The lines of standard output emitted by ADB. The standard error is discarded. 28 | * @throws GradleException if the ADB command exits with a non-zero exit code. 29 | */ 30 | public String[] execute(String... arguments) throws GradleException { 31 | final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); 32 | final ExecResult result = project.exec(execSpec -> { 33 | execSpec.setExecutable(emulatorConfiguration.getAdb()); 34 | execSpec.setArgs(Arrays.asList(arguments)); 35 | execSpec.setEnvironment(emulatorConfiguration.getEnvironmentVariableMap()); 36 | 37 | // Capture the stdout and throw away the stderr. Default is to forward to the process's stdout/stderr 38 | execSpec.setStandardOutput(stdout); 39 | execSpec.setErrorOutput(NullOutputStream.NULL_OUTPUT_STREAM); 40 | }); 41 | 42 | // Assert it ran successfully 43 | result.assertNormalExitValue(); 44 | result.rethrowFailure(); 45 | 46 | // Save the stdout to a string, split on Unix newlines, and trip whitespace which potentially includes carriage 47 | // returns on Windows. 48 | String stdoutString = new String(stdout.toByteArray(), StandardCharsets.UTF_8); 49 | project.getLogger().debug("ADB stdout: " + stdoutString); 50 | String[] lines = stdoutString.split("\\n"); 51 | for (int i = 0; i < lines.length; i++) { 52 | lines[i] = lines[i].trim(); 53 | } 54 | return lines; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/AndroidEmulatorExtension.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import org.gradle.api.Action; 4 | 5 | import java.io.File; 6 | import java.util.Collection; 7 | 8 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 9 | 10 | /** 11 | * Provides configuration for {@link AndroidEmulatorPlugin}. 12 | */ 13 | @SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") 14 | public class AndroidEmulatorExtension { 15 | public static class EmulatorExtension { 16 | private String name = null; 17 | private String device = null; 18 | private int sdkVersion = -1; 19 | private String abi = ArchitectureUtils.getEmulatorAbiString();; 20 | private boolean includeGoogleApis = false; 21 | 22 | public String getName() { 23 | return this.name; 24 | } 25 | 26 | public void setName(final String name) { 27 | this.name = name; 28 | } 29 | 30 | public void name(final String name) { 31 | this.name = name; 32 | } 33 | 34 | public String getDevice() { 35 | return this.device; 36 | } 37 | 38 | public void setDevice(final String device) { 39 | this.device = device; 40 | } 41 | 42 | public void device(final String device) { 43 | this.device = device; 44 | } 45 | 46 | public int getSdkVersion() { 47 | return this.sdkVersion; 48 | } 49 | 50 | public void setSdkVersion(final int sdkVersion) { 51 | this.sdkVersion = sdkVersion; 52 | } 53 | 54 | public void sdkVersion(final int sdkVersion) { 55 | this.sdkVersion = sdkVersion; 56 | } 57 | 58 | public String getAbi() { 59 | return this.abi; 60 | } 61 | 62 | public void setAbi(final String abi) { 63 | this.abi = abi; 64 | } 65 | 66 | public void abi(final String abi) { 67 | this.abi = abi; 68 | } 69 | 70 | public boolean getIncludeGoogleApis() { 71 | return this.includeGoogleApis; 72 | } 73 | 74 | public void setIncludeGoogleApis(final boolean includeGoogleApis) { 75 | this.includeGoogleApis = includeGoogleApis; 76 | } 77 | 78 | public void includeGoogleApis(final boolean includeGoogleApis) { 79 | this.includeGoogleApis = includeGoogleApis; 80 | } 81 | } 82 | 83 | private final EmulatorExtension emulator = new EmulatorExtension(); 84 | private File avdRoot = null; 85 | private boolean enableForAndroidTests = true; 86 | private boolean headless = false; 87 | private String[] additionalEmulatorArguments = null; 88 | private String[] additionalSdkManagerArguments = null; 89 | private boolean logEmulatorOutput = false; 90 | 91 | public EmulatorExtension getEmulator() { 92 | return this.emulator; 93 | } 94 | 95 | public void emulator(Action action) { 96 | action.execute(this.emulator); 97 | } 98 | 99 | public void setAvdRoot(final File avdRoot) { 100 | this.avdRoot = avdRoot; 101 | } 102 | 103 | public void avdRoot(final File avdRoot) { 104 | this.avdRoot = avdRoot; 105 | } 106 | 107 | public File getAvdRoot() { 108 | return this.avdRoot; 109 | } 110 | 111 | public void setEnableForAndroidTests(final boolean enableForAndroidTests) { 112 | this.enableForAndroidTests = enableForAndroidTests; 113 | } 114 | 115 | public void enableForAndroidTests(final boolean enableForAndroidTests) { 116 | this.enableForAndroidTests = enableForAndroidTests; 117 | } 118 | 119 | public boolean getEnableForAndroidTests() { 120 | return this.enableForAndroidTests; 121 | } 122 | 123 | public void headless(final boolean headless) { 124 | this.headless = headless; 125 | } 126 | 127 | public void setHeadless(final boolean headless) { 128 | this.headless = headless; 129 | } 130 | 131 | public boolean getHeadless() { 132 | return this.headless; 133 | } 134 | 135 | public void additionalEmulatorArguments(final String[] additionalEmulatorArguments) { 136 | this.additionalEmulatorArguments = clone(additionalEmulatorArguments); 137 | } 138 | 139 | public void additionalEmulatorArguments(final Collection additionalEmulatorArguments) { 140 | this.additionalEmulatorArguments = toArray(additionalEmulatorArguments); 141 | } 142 | 143 | public void setAdditionalEmulatorArguments(final String[] additionalEmulatorArguments) { 144 | this.additionalEmulatorArguments = clone(additionalEmulatorArguments); 145 | } 146 | 147 | public void setAdditionalEmulatorArguments(final Collection additionalEmulatorArguments) { 148 | this.additionalEmulatorArguments = toArray(additionalEmulatorArguments); 149 | } 150 | 151 | public void additionalSdkManagerArguments(final String[] additionalSdkManagerArguments) { 152 | this.additionalSdkManagerArguments = clone(additionalSdkManagerArguments); 153 | } 154 | 155 | public void additionalSdkManagerArguments(final Collection additionalSdkManagerArguments) { 156 | this.additionalSdkManagerArguments = toArray(additionalSdkManagerArguments); 157 | } 158 | 159 | public void setAdditionalSdkManagerArguments(final String[] additionalSdkManagerArguments) { 160 | this.additionalSdkManagerArguments = clone(additionalSdkManagerArguments); 161 | } 162 | 163 | public void setAdditionalSdkManagerArguments(final Collection additionalSdkManagerArguments) { 164 | this.additionalSdkManagerArguments = toArray(additionalSdkManagerArguments); 165 | } 166 | 167 | public String[] getAdditionalEmulatorArguments() { 168 | return clone(this.additionalEmulatorArguments); 169 | } 170 | 171 | public String[] getAdditionalSdkManagerArguments() { 172 | return clone(this.additionalSdkManagerArguments); 173 | } 174 | 175 | public void logEmulatorOutput(final boolean logEmulatorOutput) { 176 | this.logEmulatorOutput = logEmulatorOutput; 177 | } 178 | 179 | public void setLogEmulatorOutput(final boolean logEmulatorOutput) { 180 | this.logEmulatorOutput = logEmulatorOutput; 181 | } 182 | 183 | public boolean getLogEmulatorOutput() { 184 | return this.logEmulatorOutput; 185 | } 186 | 187 | /** 188 | * Helper method for cloning a potentially null array 189 | * 190 | * @param arr The array to clone 191 | * @param The type of array 192 | * @return {@code null} if {@code arr} is {@code null}, otherwise a copy of the 193 | * input array 194 | */ 195 | @SuppressFBWarnings("PZLA_PREFER_ZERO_LENGTH_ARRAYS") 196 | private static T[] clone(final T[] arr) { 197 | if (arr == null) { 198 | return null; 199 | } 200 | return arr.clone(); 201 | } 202 | 203 | /** 204 | * Helper method for converting a collection to an array 205 | * 206 | * @param collection The array to convert 207 | * @return {@code null} if {@code collection} is {@code null}, otherwise an 208 | * array containing the 209 | * contents of {@code collection}. 210 | */ 211 | @SuppressFBWarnings("PZLA_PREFER_ZERO_LENGTH_ARRAYS") 212 | private static String[] toArray(final Collection collection) { 213 | if (collection == null) { 214 | return null; 215 | } 216 | 217 | return collection.toArray(new String[collection.size()]); 218 | } 219 | } -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/AndroidEmulatorPlugin.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import com.android.build.gradle.BaseExtension; 4 | import com.android.build.gradle.internal.tasks.DeviceProviderInstrumentTestTask; 5 | import com.quittle.androidemulator.task.*; 6 | import org.gradle.api.Plugin; 7 | import org.gradle.api.Project; 8 | import org.gradle.api.Task; 9 | import org.gradle.api.tasks.TaskInstantiationException; 10 | 11 | import java.util.concurrent.atomic.AtomicReference; 12 | 13 | public class AndroidEmulatorPlugin implements Plugin { 14 | public static final String ENSURE_BASE_SDK_PERMISSIONS_TASK_NAME = "ensureBaseSdkPermissionsForAndroidEmulatorPlugin"; 15 | public static final String ENSURE_INSTALLED_SDK_PERMISSIONS_TASK_NAME = "ensureInstalledSdkPermissionsForAndroidEmulatorPlugin"; 16 | public static final String ADD_ADDITIONAL_SDK_REPOSITORIES_TASK_NAME = "addAdditionalSdkRepositoriesForAndroidEmulatorPlugin"; 17 | public static final String INSTALL_SDK_DEPENDENCIES_TASK_NAME = "installSdkDependenciesForAndroidEmulatorPlugin"; 18 | public static final String INSTALL_ANDROID_EMULATOR_SYSTEM_IMAGE_TASK_NAME = "installAndroidEmulatorSystemImageForAndroidEmulatorPlugin"; 19 | public static final String CREATE_ANDROID_EMULATOR_TASK_NAME = "createAndroidEmulator"; 20 | public static final String START_ANDROID_EMULATOR_TASK_NAME = "startAndroidEmulator"; 21 | public static final String WAIT_FOR_ANDROID_EMULATOR_TASK_NAME = "waitForAndroidEmulator"; 22 | public static final String STOP_ANDROID_EMULATOR_TASK_NAME = "stopAndroidEmulator"; 23 | 24 | private static void setUpAndroidTests(final Project project) { 25 | project.getTasks().withType( 26 | DeviceProviderInstrumentTestTask.class, task -> { 27 | task.dependsOn(WAIT_FOR_ANDROID_EMULATOR_TASK_NAME); 28 | task.finalizedBy(STOP_ANDROID_EMULATOR_TASK_NAME); 29 | }); 30 | } 31 | 32 | private static void createEnsurePermissionsTasks(final Project project, final EmulatorConfiguration emulatorConfiguration) { 33 | project.getTasks().create(ENSURE_BASE_SDK_PERMISSIONS_TASK_NAME, EnsureBaseSdkPermissions.class, emulatorConfiguration); 34 | 35 | final Task ensureInstalledSdkPermissionsTask = project.getTasks().create(ENSURE_INSTALLED_SDK_PERMISSIONS_TASK_NAME, EnsureInstalledSdkPermissionsTask.class, emulatorConfiguration); 36 | ensureInstalledSdkPermissionsTask.dependsOn(INSTALL_SDK_DEPENDENCIES_TASK_NAME); 37 | } 38 | 39 | private static void createAddAdditionalSdkRepositoriesTask(final Project project) { 40 | project.getTasks().create(ADD_ADDITIONAL_SDK_REPOSITORIES_TASK_NAME, AddAdditionalSdkRepositoriesTask.class); 41 | } 42 | 43 | private static void createInstallSdkDependenciesTask(final Project project, final EmulatorConfiguration emulatorConfiguration) { 44 | final Task task = project.getTasks().create(INSTALL_SDK_DEPENDENCIES_TASK_NAME, InstallSdkDependenciesTask.class, emulatorConfiguration); 45 | task.dependsOn(ENSURE_BASE_SDK_PERMISSIONS_TASK_NAME); 46 | } 47 | 48 | private static void createInstallEmulatorSystemImageTask(final Project project, final EmulatorConfiguration emulatorConfiguration) { 49 | final Task task = project.getTasks().create(INSTALL_ANDROID_EMULATOR_SYSTEM_IMAGE_TASK_NAME, InstallAndroidEmulatorSystemImageTask.class, emulatorConfiguration); 50 | task.dependsOn(ENSURE_INSTALLED_SDK_PERMISSIONS_TASK_NAME, ADD_ADDITIONAL_SDK_REPOSITORIES_TASK_NAME); 51 | } 52 | 53 | private static void createCreateEmulatorTask(final Project project, final EmulatorConfiguration emulatorConfiguration) { 54 | final Task createEmulatorTask = project.getTasks().create( 55 | CREATE_ANDROID_EMULATOR_TASK_NAME, CreateEmulatorExecTask.class, emulatorConfiguration); 56 | createEmulatorTask.dependsOn( 57 | INSTALL_ANDROID_EMULATOR_SYSTEM_IMAGE_TASK_NAME, 58 | INSTALL_SDK_DEPENDENCIES_TASK_NAME, 59 | ENSURE_INSTALLED_SDK_PERMISSIONS_TASK_NAME); 60 | } 61 | 62 | private static void createEmulatorLifecycleTasks(final Project project, final EmulatorConfiguration emulatorConfiguration, final AdbProxy adbProxy) { 63 | final AtomicReference emulatorProcess = new AtomicReference<>(); 64 | final AtomicReference waitForDeviceProcess = new AtomicReference<>(); 65 | 66 | createStartEmulatorTask(project, emulatorConfiguration, adbProxy, emulatorProcess, waitForDeviceProcess); 67 | createWaitForEmulatorTask(project, emulatorConfiguration, waitForDeviceProcess); 68 | createStopEmulatorTask(project, emulatorProcess); 69 | } 70 | 71 | private static void createStartEmulatorTask( 72 | final Project project, 73 | final EmulatorConfiguration emulatorConfiguration, 74 | final AdbProxy adbProxy, 75 | final AtomicReference emulatorProcess, 76 | final AtomicReference waitForDeviceProcess) { 77 | final Task task = project.getTasks().create(START_ANDROID_EMULATOR_TASK_NAME, StartAndroidEmulatorTask.class, 78 | emulatorConfiguration, adbProxy, emulatorProcess, waitForDeviceProcess); 79 | 80 | task.dependsOn(ENSURE_INSTALLED_SDK_PERMISSIONS_TASK_NAME, INSTALL_SDK_DEPENDENCIES_TASK_NAME, CREATE_ANDROID_EMULATOR_TASK_NAME); 81 | task.finalizedBy(STOP_ANDROID_EMULATOR_TASK_NAME); 82 | } 83 | 84 | private static void createWaitForEmulatorTask(final Project project, final EmulatorConfiguration emulatorConfiguration, final AtomicReference waitForDeviceProcess) { 85 | final Task task = project.getTasks().create(WAIT_FOR_ANDROID_EMULATOR_TASK_NAME, WaitForAndroidEmulatorTask.class, emulatorConfiguration, waitForDeviceProcess); 86 | 87 | task.dependsOn(ENSURE_BASE_SDK_PERMISSIONS_TASK_NAME, START_ANDROID_EMULATOR_TASK_NAME); 88 | } 89 | 90 | private static void createStopEmulatorTask(final Project project, final AtomicReference emulatorProcess) { 91 | final Task task = project.getTasks().create(STOP_ANDROID_EMULATOR_TASK_NAME, StopAndroidEmulatorTask.class, emulatorProcess); 92 | 93 | task.dependsOn(ENSURE_INSTALLED_SDK_PERMISSIONS_TASK_NAME, START_ANDROID_EMULATOR_TASK_NAME); 94 | task.mustRunAfter(WAIT_FOR_ANDROID_EMULATOR_TASK_NAME); 95 | } 96 | 97 | @Override 98 | public void apply(final Project project) { 99 | final AndroidEmulatorExtension extension = 100 | project.getExtensions().create("androidEmulator", AndroidEmulatorExtension.class); 101 | 102 | project.afterEvaluate(p -> { 103 | final BaseExtension androidExtension = p.getExtensions().findByType(BaseExtension.class); 104 | if (androidExtension == null) { 105 | throw new TaskInstantiationException("Android extension not found. Make sure the Android plugin is applied"); 106 | } 107 | 108 | final EmulatorConfiguration emulatorConfiguration = new EmulatorConfiguration(project, androidExtension, extension); 109 | final AdbProxy adbProxy = new AdbProxy(project, emulatorConfiguration); 110 | 111 | if (emulatorConfiguration.getEnableForAndroidTests()) { 112 | setUpAndroidTests(p); 113 | } 114 | 115 | createEnsurePermissionsTasks(p, emulatorConfiguration); 116 | createAddAdditionalSdkRepositoriesTask(p); 117 | createInstallSdkDependenciesTask(p, emulatorConfiguration); 118 | createInstallEmulatorSystemImageTask(p, emulatorConfiguration); 119 | createCreateEmulatorTask(p, emulatorConfiguration); 120 | createEmulatorLifecycleTasks(p, emulatorConfiguration, adbProxy); 121 | }); 122 | } 123 | } -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/AndroidRepositories.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import com.android.prefs.AndroidLocationsException; 4 | import com.android.prefs.AndroidLocationsSingleton; 5 | 6 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 7 | 8 | import java.io.*; 9 | import java.lang.reflect.Method; 10 | import java.net.URL; 11 | import java.util.Map; 12 | import java.util.Properties; 13 | 14 | /** 15 | * Manages Android repository configuration files. Does not manipulate files 16 | * until {@link #save} is called. 17 | */ 18 | public class AndroidRepositories { 19 | private static final String PROPERTIES_COUNT_KEY = "count"; 20 | private static final String PROPERTIES_ENABLED_KEY = "enabled"; 21 | private static final String PROPERTIES_SRC_KEY = "src"; 22 | private static final String PROPERTIES_DISP_KEY = "disp"; 23 | 24 | private final File repositoriesFile; 25 | private final Properties properties; 26 | 27 | /** 28 | * Loads the configuration properties file from disk. Avoid holding onto a 29 | * reference to this for a long time as the file may be manipulated in between. 30 | * 31 | * @return a repositories file for manipulation. 32 | * @throws AndroidRepositoryException if something goes wrong finding or reading 33 | * the config file on disk. 34 | */ 35 | public static AndroidRepositories load() throws AndroidRepositoryException { 36 | final File repositoriesFile = getRepositoriesFile(); 37 | 38 | final Properties props = new Properties(); 39 | if (repositoriesFile.exists()) { 40 | try (final InputStream is = new FileInputStream(repositoriesFile)) { 41 | props.load(is); 42 | } catch (final IOException e) { 43 | throw new AndroidRepositoryException("Unable to read repositories.cfg file", e); 44 | } 45 | } 46 | 47 | return new AndroidRepositories(repositoriesFile, props); 48 | } 49 | 50 | /** 51 | * Writes updates to the file on disk. May be called multiple times and 52 | * overrides, rather than updates, the existing file. 53 | * 54 | * @throws AndroidRepositoryException if unable to write the update. 55 | */ 56 | public void save() throws AndroidRepositoryException { 57 | try (final OutputStream os = new FileOutputStream(this.repositoriesFile)) { 58 | this.properties.store(os, "Last updated by the com.quittle.android-emulator Gradle plugin"); 59 | } catch (final IOException e) { 60 | throw new AndroidRepositoryException("Unable to save repositories.cfg", e); 61 | } 62 | } 63 | 64 | public void addRepository(final String friendlyName, final URL url) throws AndroidRepositoryException { 65 | final int curCount; 66 | try { 67 | curCount = Integer.parseInt(properties.getProperty(PROPERTIES_COUNT_KEY, "0"), 10); 68 | } catch (final NumberFormatException e) { 69 | throw new AndroidRepositoryException("Unable to parse count key of repositories.cfg", e); 70 | } 71 | 72 | final String urlString = url.toString(); 73 | 74 | for (final Map.Entry entry : properties.entrySet()) { 75 | final String key = (String) entry.getKey(); 76 | final String value = (String) entry.getValue(); 77 | 78 | if (key.startsWith(PROPERTIES_SRC_KEY) && value.equals(urlString)) { 79 | final int index; 80 | try { 81 | index = Integer.parseInt(key.substring(3), 10); 82 | } catch (final NumberFormatException e) { 83 | throw new AndroidRepositoryException("Unable to parse index of repositories.cfg key: " + key, e); 84 | } 85 | 86 | properties.setProperty(buildPropertyIndexedName(PROPERTIES_ENABLED_KEY, index), "true"); 87 | return; 88 | } 89 | } 90 | 91 | properties.setProperty(buildPropertyIndexedName(PROPERTIES_ENABLED_KEY, curCount), "true"); 92 | properties.setProperty(buildPropertyIndexedName(PROPERTIES_DISP_KEY, curCount), friendlyName); 93 | properties.setProperty(buildPropertyIndexedName(PROPERTIES_SRC_KEY, curCount), urlString); 94 | properties.setProperty(PROPERTIES_COUNT_KEY, String.valueOf(curCount + 1)); 95 | } 96 | 97 | /** 98 | * The location of the repositories configuration file used by the Android SDK 99 | * tools. This file may not exist. 100 | * 101 | * @return The configuration file location. 102 | * @throws AndroidRepositoryException if unable to determine its location. 103 | */ 104 | @SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Broad catch to handle both reflection exceptions and AndroidLocationExceptions that would need to be loaded with reflection anyway") 105 | public static File getRepositoriesFile() throws AndroidRepositoryException { 106 | final String errorMessage = "Unable to find android home directory"; 107 | try { 108 | try { 109 | final File folder = AndroidLocationsSingleton.INSTANCE.getPrefsLocation().toFile(); 110 | return new File(folder, "repositories.cfg"); 111 | } catch (final AndroidLocationsException e) { 112 | throw new AndroidRepositoryException(errorMessage, e); 113 | } 114 | } catch (final NoClassDefFoundError _e) { 115 | // This is expected to occur when running with older versions of the plugin 116 | 117 | try { 118 | final Class clazz = Class.forName("com.android.prefs.AndroidLocation"); 119 | final Method method = clazz.getDeclaredMethod("getFolder"); 120 | final String folder = (String) method.invoke(null); 121 | return new File(folder, "repositories.cfg"); 122 | } catch (final Exception e) { 123 | // This handles all manner of reflection, casting, and exceptions that could be 124 | // thrown by calling getFolder() 125 | throw new AndroidRepositoryException("Unable to find android home directory", e); 126 | } 127 | } 128 | } 129 | 130 | /** 131 | * Source: 132 | * https://android.googlesource.com/platform/sdk/+/tools_r21/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/repository/sources/SdkSources.java#289 133 | */ 134 | private static String buildPropertyIndexedName(final String key, final int index) { 135 | return String.format("%s%02d", key, index); 136 | } 137 | 138 | private AndroidRepositories(final File repositoriesFile, final Properties properties) { 139 | this.repositoriesFile = repositoriesFile; 140 | this.properties = properties; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/AndroidRepositoryException.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | public class AndroidRepositoryException extends Exception { 4 | private static final long serialVersionUID = 1; 5 | 6 | public AndroidRepositoryException(final String message, final Throwable cause) { 7 | super(message, cause); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/ArchitectureUtils.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class ArchitectureUtils { 8 | public enum Architecture { 9 | ARCH_ARMEABI_V7A("armeabi-v7a", "arm-v7", "armv7", "arm", "arm32"), 10 | ARCH_ARMEABI("armeabi"), 11 | ARCH_ARM64_V8A("arm64-v8a", "arm64", "aarch64"), 12 | ARCH_X86("x86", "i386", "ia-32", "i686"), 13 | ARCH_X86_64("x86_64", "amd64", "x64", "x86-64", "ia-64", "ia64"); 14 | 15 | public final String emulatorArchitecture; 16 | public final Set allValues; 17 | 18 | Architecture(final String emulatorArchitecture, final String... rest) { 19 | this.emulatorArchitecture = emulatorArchitecture; 20 | final Set values = new HashSet<>(Arrays.asList(rest)); 21 | values.add(emulatorArchitecture); 22 | this.allValues = values; 23 | } 24 | } 25 | 26 | public static String getEmulatorAbiString() { 27 | final String osArch = System.getProperty("os.arch"); 28 | for (final Architecture architecture : Architecture.values()) { 29 | if (architecture.allValues.contains(osArch)) { 30 | return architecture.emulatorArchitecture; 31 | } 32 | } 33 | return null; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/CollectionUtils.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public final class CollectionUtils { 8 | /** 9 | * Converts the arguments to mutable list. This is preferable to {@link Arrays#asList} when a mutable list is 10 | * required. 11 | * @param The type of the contents of the list 12 | * @param values The values to be part of the list 13 | * @return A mutable list of unspecified type. 14 | */ 15 | @SafeVarargs 16 | @SuppressWarnings("varargs") 17 | public static List mutableListOf(T... values) { 18 | return new ArrayList<>(Arrays.asList(values)); 19 | } 20 | 21 | private CollectionUtils() {} 22 | } 23 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/EmulatorConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import com.android.build.gradle.BaseExtension; 4 | import com.android.builder.model.ApiVersion; 5 | import org.apache.tools.ant.taskdefs.condition.Os; 6 | import org.gradle.api.Project; 7 | 8 | import java.io.File; 9 | import java.util.ArrayList; 10 | import java.util.Arrays; 11 | import java.util.Collections; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | @SuppressWarnings("PMD.AvoidDuplicateLiterals") 17 | public class EmulatorConfiguration { 18 | /** 19 | * Paths to a folder containing {@code sdkmanager} relative to $SDK_ROOT. 20 | * {@code null} entries indicate that the 21 | * folder in the path should be a version number and to select the highest 22 | * revision possible. This 23 | * {@code sdkmanager} will be used to bootstrap the plugin and install a newer 24 | * version. The earlier entries are 25 | * preferred over later ones. 26 | */ 27 | private static final String[][] POTENTIAL_INITIAL_SDK_MANAGER_PATHS = new String[][] { 28 | // This is used if cmdline-tools is downloaded separately and copied into 29 | // $SDK_ROOT 30 | new String[] { "cmdline-tools", "tools", "bin" }, 31 | // This is used when cmdline-tools;latest is installed via sdkmanager 32 | new String[] { "cmdline-tools", "latest", "bin" }, 33 | // This is used when a specific version of the cmdline-tools package is 34 | // installed via sdkmanager 35 | new String[] { "cmdline-tools", null, "bin" }, 36 | // This is used when the sdkmanager is provided by the legacy sdk tools which 37 | // haven't been updated in years. 38 | new String[] { "tools", "bin" }, 39 | }; 40 | 41 | private final File sdkRoot; 42 | private final File avdRoot; 43 | private final Map environmentVariableMap; 44 | private final boolean enableForAndroidTests; 45 | private final List additionalEmulatorArguments; 46 | private final List additionalSdkManagerArguments; 47 | private final boolean logEmulatorOutput; 48 | private final String androidVersion; 49 | private final String flavor; 50 | private final String abi; 51 | private final String systemImagePackageName; 52 | private final String emulatorName; 53 | private final String deviceType; 54 | private Integer emulatorPort; 55 | 56 | EmulatorConfiguration(final Project project, final BaseExtension androidExtension, 57 | final AndroidEmulatorExtension androidEmulatorExtension) { 58 | this.sdkRoot = androidExtension.getSdkDirectory(); 59 | 60 | if (androidEmulatorExtension.getAvdRoot() != null) { 61 | this.avdRoot = androidEmulatorExtension.getAvdRoot(); 62 | } else { 63 | this.avdRoot = new File(project.getBuildDir(), "android-avd-root"); 64 | } 65 | 66 | if (this.sdkRoot == null) { 67 | throw new RuntimeException("Unable to initialize com.quittle.android-emulator " + 68 | "because Android plugin has not been initialized with an SDK root."); 69 | } 70 | 71 | final Map environmentVariableMap = new HashMap<>(); 72 | environmentVariableMap.put("ANDROID_SDK_ROOT", sdkRoot.getAbsolutePath()); 73 | environmentVariableMap.put("ANDROID_HOME", sdkRoot.getAbsolutePath()); 74 | environmentVariableMap.put("ANDROID_AVD_HOME", avdRoot.getAbsolutePath()); 75 | this.environmentVariableMap = Collections.unmodifiableMap(environmentVariableMap); 76 | 77 | this.enableForAndroidTests = androidEmulatorExtension.getEnableForAndroidTests(); 78 | 79 | this.additionalEmulatorArguments = new ArrayList<>(); 80 | if (androidEmulatorExtension.getHeadless()) { 81 | additionalEmulatorArguments.add("-no-skin"); 82 | additionalEmulatorArguments.add("-no-audio"); 83 | additionalEmulatorArguments.add("-no-window"); 84 | } 85 | final String[] additionalEmulatorArgs = androidEmulatorExtension.getAdditionalEmulatorArguments(); 86 | if (additionalEmulatorArgs != null) { 87 | additionalEmulatorArguments.addAll(Arrays.asList(additionalEmulatorArgs)); 88 | } 89 | 90 | final String[] additionalSdkManagerArgs = androidEmulatorExtension.getAdditionalSdkManagerArguments(); 91 | if (additionalSdkManagerArgs != null) { 92 | additionalSdkManagerArguments = new ArrayList<>(); 93 | additionalSdkManagerArguments.addAll(Arrays.asList(additionalSdkManagerArgs)); 94 | } else { 95 | additionalSdkManagerArguments = Collections.emptyList(); 96 | } 97 | 98 | this.logEmulatorOutput = androidEmulatorExtension.getLogEmulatorOutput(); 99 | 100 | final AndroidEmulatorExtension.EmulatorExtension emulator = androidEmulatorExtension.getEmulator(); 101 | int sdkVersion = emulator.getSdkVersion(); 102 | if (sdkVersion <= 0) { 103 | ApiVersion version = androidExtension.getDefaultConfig().getTargetSdkVersion(); 104 | if (version == null) { 105 | version = androidExtension.getDefaultConfig().getMinSdkVersion(); 106 | } 107 | 108 | if (version != null) { 109 | sdkVersion = version.getApiLevel(); 110 | } else { 111 | sdkVersion = 10; // Earliest version supported out of the box by the SDK Manager still 112 | } 113 | } 114 | this.androidVersion = String.format("android-%d", sdkVersion); 115 | this.flavor = emulator.getIncludeGoogleApis() ? "google_apis" : "default"; 116 | this.abi = emulator.getAbi(); 117 | this.systemImagePackageName = String.format("system-images;%s;%s;%s", androidVersion, flavor, abi); 118 | this.deviceType = emulator.getDevice(); 119 | 120 | if (emulator.getName() != null) { 121 | this.emulatorName = emulator.getName(); 122 | } else { 123 | this.emulatorName = String.format("generated-%s_%s-%s", androidVersion, abi, flavor); 124 | } 125 | } 126 | 127 | private static File sdkFile(final File sdkRoot, final String... pathParts) { 128 | File path = sdkRoot; 129 | for (final String part : pathParts) { 130 | if (part != null) { 131 | path = new File(path, part); 132 | } else if (!path.isDirectory()) { 133 | return null; 134 | } else { 135 | File[] children = path.listFiles(); 136 | 137 | if (children == null || children.length == 0) { 138 | return null; 139 | } 140 | path = Arrays.stream(children) 141 | .max((a, b) -> new VersionComparator().compare(a.getName(), b.getName())) 142 | .orElseThrow(); 143 | } 144 | } 145 | 146 | return path; 147 | } 148 | 149 | public File getSdkRoot() { 150 | return sdkRoot; 151 | } 152 | 153 | public File sdkFile(String... path) { 154 | return sdkFile(sdkRoot, path); 155 | } 156 | 157 | /** 158 | * Provides the initial {@code sdkmanager} used to install the latest version, 159 | * retrieved later by this plugin via {@link #getCmdLineToolsSdkManager}. 160 | * 161 | * @return The {@code sdkmanager} file location, which is guaranteed to exist 162 | * and be a file if returned. 163 | * @throws RuntimeException if no {@code sdkmanager} to use can be found on 164 | * disk. 165 | */ 166 | public File getSdkManager() throws RuntimeException { 167 | for (final String[] path : POTENTIAL_INITIAL_SDK_MANAGER_PATHS) { 168 | final File basePath = sdkFile(sdkRoot, path); 169 | if (basePath != null) { 170 | final File sdkmanager; 171 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 172 | sdkmanager = new File(basePath, "sdkmanager.bat"); 173 | } else { 174 | sdkmanager = new File(basePath, "sdkmanager"); 175 | } 176 | if (sdkmanager.isFile()) { 177 | return sdkmanager; 178 | } 179 | } 180 | } 181 | throw new RuntimeException("Unable to find a valid sdkmanager to use."); 182 | } 183 | 184 | public File getCmdLineToolsSdkManager() { 185 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 186 | return sdkFile(sdkRoot, "cmdline-tools", "latest", "bin", "sdkmanager.bat"); 187 | } else { 188 | return sdkFile(sdkRoot, "cmdline-tools", "latest", "bin", "sdkmanager"); 189 | } 190 | } 191 | 192 | public File getAvdManager() { 193 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 194 | return sdkFile(sdkRoot, "cmdline-tools", "latest", "bin", "avdmanager.bat"); 195 | } else { 196 | return sdkFile(sdkRoot, "cmdline-tools", "latest", "bin", "avdmanager"); 197 | } 198 | } 199 | 200 | public File getEmulator() { 201 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 202 | return sdkFile(sdkRoot, "emulator", "emulator.exe"); 203 | } else { 204 | return sdkFile(sdkRoot, "emulator", "emulator"); 205 | } 206 | } 207 | 208 | public File getAdb() { 209 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 210 | return sdkFile(sdkRoot, "platform-tools", "adb.exe"); 211 | } else { 212 | return sdkFile(sdkRoot, "platform-tools", "adb"); 213 | } 214 | } 215 | 216 | public File getAvdRoot() { 217 | return avdRoot; 218 | } 219 | 220 | public Map getEnvironmentVariableMap() { 221 | return environmentVariableMap; 222 | } 223 | 224 | public boolean getEnableForAndroidTests() { 225 | return enableForAndroidTests; 226 | } 227 | 228 | public List getAdditionalEmulatorArguments() { 229 | return additionalEmulatorArguments; 230 | } 231 | 232 | public List getAdditionalSdkManagerArguments() { 233 | return additionalSdkManagerArguments; 234 | } 235 | 236 | public boolean getLogEmulatorOutput() { 237 | return logEmulatorOutput; 238 | } 239 | 240 | public String getAndroidVersion() { 241 | return androidVersion; 242 | } 243 | 244 | public String getFlavor() { 245 | return flavor; 246 | } 247 | 248 | public String getAbi() { 249 | return abi; 250 | } 251 | 252 | public String getSystemImagePackageName() { 253 | return systemImagePackageName; 254 | } 255 | 256 | public String getEmulatorName() { 257 | return emulatorName; 258 | } 259 | 260 | public String getDeviceType() { 261 | return deviceType; 262 | } 263 | 264 | /** 265 | * When the plugin starts the emulator, it should bind it to a specify a port in 266 | * the range 5554 to 5682 and call this method to set it for other tasks to use. 267 | * See https://developer.android.com/studio/run/emulator-commandline#common for 268 | * more details. 269 | * 270 | * @param port The port to be bound to the emulator. 271 | */ 272 | public void setEmulatorPort(final int port) { 273 | this.emulatorPort = port; 274 | } 275 | 276 | /** 277 | * The port the emulator was bound to in the range 5554 to 5682. Note that if 278 | * bound the port will always be even. 279 | * See https://developer.android.com/studio/run/emulator-commandline#common for 280 | * more details. 281 | * 282 | * @return The port the emulator should be bound to or null if not bound yet. 283 | */ 284 | public Integer getEmulatorPort() { 285 | return this.emulatorPort; 286 | } 287 | } 288 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/VersionComparator.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import java.io.Serializable; 4 | import java.util.Arrays; 5 | import java.util.Comparator; 6 | 7 | public class VersionComparator implements Comparator, Serializable { 8 | private static final long serialVersionUID = 0; 9 | 10 | @Override 11 | public int compare(String a, String b) { 12 | final int[] aParts; 13 | try { 14 | aParts = stringToVersion(a); 15 | } catch (NumberFormatException _e) { 16 | return -1; 17 | } 18 | 19 | final int[] bParts; 20 | try { 21 | bParts = stringToVersion(b); 22 | } catch (NumberFormatException _e) { 23 | return 1; 24 | } 25 | 26 | for (int i = 0; i < aParts.length; i++) { 27 | if (i >= bParts.length) { 28 | return 1; 29 | } 30 | 31 | final int aVersion = aParts[i]; 32 | final int bVersion = bParts[i]; 33 | 34 | if (aVersion > bVersion) { 35 | return 1; 36 | } else if (aVersion < bVersion) { 37 | return -1; 38 | } 39 | } 40 | 41 | if (bParts.length > aParts.length) { 42 | return -1; 43 | } 44 | 45 | return 0; 46 | } 47 | 48 | private static int[] stringToVersion(String version) { 49 | final String[] versionParts = version.split("\\."); 50 | return Arrays.stream(versionParts) 51 | .mapToInt(Integer::parseInt) 52 | .toArray(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/AddAdditionalSdkRepositoriesTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.AndroidRepositories; 4 | import com.quittle.androidemulator.AndroidRepositoryException; 5 | import org.gradle.api.DefaultTask; 6 | import org.gradle.api.tasks.TaskAction; 7 | import org.gradle.api.tasks.TaskExecutionException; 8 | 9 | import java.net.MalformedURLException; 10 | import java.net.URL; 11 | 12 | public class AddAdditionalSdkRepositoriesTask extends DefaultTask { 13 | @TaskAction 14 | public void act() { 15 | try { 16 | final AndroidRepositories repositories = AndroidRepositories.load(); 17 | repositories.addRepository("Legacy Google APIs System Images", new URL("https://dl.google.com/android/repository/sys-img/google_apis/sys-img.xml")); 18 | repositories.addRepository("Legacy Android System Images", new URL("https://dl.google.com/android/repository/sys-img/android/sys-img.xml")); 19 | repositories.save(); 20 | } catch (AndroidRepositoryException | MalformedURLException e) { 21 | throw new TaskExecutionException(this, e); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/AndroidEmulatorBaseExecTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | import org.gradle.api.tasks.AbstractExecTask; 5 | 6 | import java.io.ByteArrayInputStream; 7 | import java.io.InputStream; 8 | import java.nio.charset.StandardCharsets; 9 | 10 | public class AndroidEmulatorBaseExecTask> extends AbstractExecTask { 11 | private final EmulatorConfiguration emulatorConfiguration; 12 | 13 | public AndroidEmulatorBaseExecTask(final Class taskType, final EmulatorConfiguration emulatorConfiguration) { 14 | super(taskType); 15 | 16 | this.emulatorConfiguration = emulatorConfiguration; 17 | 18 | this.environment(emulatorConfiguration.getEnvironmentVariableMap()); 19 | // Environment isn't tracked by default to prevent unrelated environment changes changing inpts 20 | this.getInputs().property("environmentMap", emulatorConfiguration.getEnvironmentVariableMap()); 21 | } 22 | 23 | /** 24 | * Generates the argument for specifying {@code --sdk_root} for the new {@code sdkmanager} which requires it. 25 | * @return The sdkmanager argument specifying the sdk root 26 | */ 27 | protected String buildSdkRootArgument() { 28 | return "--sdk_root=" + emulatorConfiguration.getSdkRoot().getAbsolutePath(); 29 | } 30 | 31 | /** 32 | * Provides an input stream from the lines of input. This is intended to be used to generate the standard input for 33 | * exec tasks. 34 | * @param lines The input lines 35 | * @return The generated input stream. 36 | */ 37 | protected InputStream buildStandardInLines(String... lines) { 38 | final String string = String.join(System.lineSeparator(), lines); 39 | final byte[] bytes = string.getBytes(StandardCharsets.UTF_8); 40 | return new ByteArrayInputStream(bytes); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/CreateEmulatorExecTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | 5 | import javax.inject.Inject; 6 | import java.io.File; 7 | import java.util.List; 8 | 9 | import static com.quittle.androidemulator.CollectionUtils.mutableListOf; 10 | 11 | public class CreateEmulatorExecTask extends AndroidEmulatorBaseExecTask { 12 | @Inject 13 | public CreateEmulatorExecTask(final EmulatorConfiguration emulatorConfiguration) { 14 | super(CreateEmulatorExecTask.class, emulatorConfiguration); 15 | 16 | final String emulatorName = emulatorConfiguration.getEmulatorName(); 17 | final File avdRoot = emulatorConfiguration.getAvdRoot(); 18 | final String deviceType = emulatorConfiguration.getDeviceType(); 19 | final String systemImagePackageName = emulatorConfiguration.getSystemImagePackageName(); 20 | 21 | this.setExecutable(emulatorConfiguration.getAvdManager()); 22 | List args = mutableListOf( 23 | "create", 24 | "avd", 25 | "--name", emulatorName, 26 | "--package", systemImagePackageName, 27 | "--force"); 28 | if (deviceType != null) { 29 | args.add("--device"); 30 | args.add(deviceType); 31 | } 32 | this.setArgs(args); 33 | this.setStandardInput(buildStandardInLines("no")); 34 | 35 | this.getOutputs().dir(new File(avdRoot, emulatorName + ".avd")); 36 | this.getOutputs().file(new File(avdRoot, emulatorName + ".ini")); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/EnsureBaseSdkPermissions.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | import org.gradle.api.DefaultTask; 5 | import org.gradle.api.tasks.InputFiles; 6 | import org.gradle.api.tasks.TaskAction; 7 | 8 | import javax.inject.Inject; 9 | import java.io.File; 10 | 11 | public class EnsureBaseSdkPermissions extends EnsureFilesAreExecutableTask { 12 | private final EmulatorConfiguration emulatorConfiguration; 13 | 14 | @Inject 15 | public EnsureBaseSdkPermissions(EmulatorConfiguration emulatorConfiguration) { 16 | this.emulatorConfiguration = emulatorConfiguration; 17 | } 18 | 19 | @InputFiles 20 | @Override 21 | protected File[] getFilesToMakeExecutable() { 22 | return new File[] { 23 | emulatorConfiguration.getSdkManager(), 24 | emulatorConfiguration.getAdb() 25 | }; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/EnsureFilesAreExecutableTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import org.gradle.api.DefaultTask; 4 | import org.gradle.api.tasks.InputFiles; 5 | import org.gradle.api.tasks.TaskAction; 6 | 7 | import java.io.File; 8 | 9 | /** 10 | * Ensures given files are executable, and if not, tries promote file to be executable, failing if unable to do so. 11 | */ 12 | public abstract class EnsureFilesAreExecutableTask extends DefaultTask { 13 | @TaskAction 14 | public void act() { 15 | for (final File file : getFilesToMakeExecutable()) { 16 | // First check if file is executable. In most environments sdk binaries are already executable. 17 | // In some environments your process is not an owner of the file and can't change permission. 18 | // For example docker or some CI systems in which case these files must already be executable. 19 | if (!(file.canExecute() || file.setExecutable(true))) { 20 | throw new RuntimeException(String.format("Unable to ensure %s is executable", file.getName())); 21 | } 22 | } 23 | } 24 | 25 | @InputFiles 26 | abstract protected File[] getFilesToMakeExecutable(); 27 | } 28 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/EnsureInstalledSdkPermissionsTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | import org.gradle.api.tasks.InputFiles; 5 | 6 | import javax.inject.Inject; 7 | import java.io.File; 8 | 9 | public class EnsureInstalledSdkPermissionsTask extends EnsureFilesAreExecutableTask { 10 | private final EmulatorConfiguration emulatorConfiguration; 11 | 12 | @Inject 13 | public EnsureInstalledSdkPermissionsTask(final EmulatorConfiguration emulatorConfiguration) { 14 | this.emulatorConfiguration = emulatorConfiguration; 15 | } 16 | 17 | @InputFiles 18 | @Override 19 | protected File[] getFilesToMakeExecutable() { 20 | return new File[] { 21 | emulatorConfiguration.getCmdLineToolsSdkManager(), 22 | emulatorConfiguration.getAvdManager() 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/InstallAndroidEmulatorSystemImageTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | 5 | import javax.inject.Inject; 6 | import java.util.Arrays; 7 | 8 | public class InstallAndroidEmulatorSystemImageTask extends AndroidEmulatorBaseExecTask { 9 | @Inject 10 | public InstallAndroidEmulatorSystemImageTask(final EmulatorConfiguration emulatorConfiguration) { 11 | super(InstallAndroidEmulatorSystemImageTask.class, emulatorConfiguration); 12 | 13 | this.setExecutable(emulatorConfiguration.getCmdLineToolsSdkManager()); 14 | this.args(Arrays.asList(buildSdkRootArgument(), emulatorConfiguration.getSystemImagePackageName())); 15 | this.args(emulatorConfiguration.getAdditionalSdkManagerArguments()); 16 | this.setStandardInput(buildStandardInLines("y")); 17 | this.getOutputs().dir(emulatorConfiguration.sdkFile("system-images", emulatorConfiguration.getAndroidVersion(), emulatorConfiguration.getFlavor(), emulatorConfiguration.getAbi())); 18 | this.getOutputs().file(emulatorConfiguration.sdkFile("system-images", emulatorConfiguration.getAndroidVersion(), emulatorConfiguration.getFlavor(), emulatorConfiguration.getAbi(), "system.img")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/InstallSdkDependenciesTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | import org.gradle.api.Action; 5 | import org.gradle.api.Task; 6 | 7 | import javax.inject.Inject; 8 | import java.io.File; 9 | import java.util.Arrays; 10 | 11 | public class InstallSdkDependenciesTask extends AndroidEmulatorBaseExecTask { 12 | @Inject 13 | public InstallSdkDependenciesTask(final EmulatorConfiguration emulatorConfiguration) { 14 | super(InstallSdkDependenciesTask.class, emulatorConfiguration); 15 | 16 | this.setExecutable(emulatorConfiguration.getSdkManager()); 17 | this.args(Arrays.asList(buildSdkRootArgument(), "emulator", "cmdline-tools;latest", "platform-tools")); 18 | this.args(emulatorConfiguration.getAdditionalSdkManagerArguments()); 19 | this.setStandardInput(buildStandardInLines("y")); 20 | this.getOutputs().dir(new File(emulatorConfiguration.getSdkRoot(), "emulator")); 21 | 22 | // This cannot be a lambda or the task will never be considered up-to-date 23 | this.doLast(new FixPermissions(emulatorConfiguration)); 24 | } 25 | 26 | private static class FixPermissions implements Action { 27 | private final EmulatorConfiguration emulatorConfiguration; 28 | 29 | private FixPermissions(final EmulatorConfiguration emulatorConfiguration) { 30 | this.emulatorConfiguration = emulatorConfiguration; 31 | } 32 | 33 | @Override 34 | public void execute(Task task) { 35 | if (!emulatorConfiguration.getEmulator().setExecutable(true)) { 36 | throw new RuntimeException("Unable to make android emulator executable"); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/ProcessDestroyer.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import org.gradle.api.Project; 4 | import org.slf4j.Logger; 5 | 6 | import java.util.List; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.function.UnaryOperator; 9 | import java.util.stream.Collectors; 10 | 11 | /** 12 | * Utility that attempts to destroy a process. This operator always returns null, which is useful for nulling out an 13 | * {@link java.util.concurrent.atomic.AtomicReference} with {@code processReference.getAndUpdate(processDestroyer)}. 14 | */ 15 | class ProcessDestroyer implements UnaryOperator { 16 | private static final long PROCESS_TERMINATION_TIMEOUT_SEC = 15; 17 | 18 | private final Logger logger; 19 | 20 | ProcessDestroyer(final Project project) { 21 | this.logger = project.getLogger(); 22 | } 23 | 24 | @Override 25 | public Process apply(final Process process) { 26 | if (process != null) { 27 | List descendants = process.descendants().collect(Collectors.toList()); 28 | // Use a non-forceful destroy first to allow the process to gracefully shutdown. With the android emulator 29 | // this includes creating a snapshot of the current state for warm boots in subsequent runs. On unix-like 30 | // systems this usually translates to raising a SIGTERM signal. 31 | process.destroy(); 32 | try { 33 | final boolean processDidExit = process.waitFor(PROCESS_TERMINATION_TIMEOUT_SEC, TimeUnit.SECONDS); 34 | 35 | // Forcibly destroy the process. On unix-like systems this usually translates to raising a SIGKILL 36 | // signal. 37 | if (!processDidExit) { 38 | process.destroyForcibly(); 39 | process.waitFor(PROCESS_TERMINATION_TIMEOUT_SEC, TimeUnit.SECONDS); 40 | } 41 | // if a process has not destroyed descendants 42 | descendants.forEach(ProcessHandle::destroyForcibly); 43 | } catch (InterruptedException e) { 44 | logger.debug("Interrupted while waiting for process to be destroyed", e); 45 | // It is likely fine to allow the failure and move on. The termination of the gradle process might stop 46 | // the process or stop soon after the timeout. 47 | } 48 | } 49 | 50 | return null; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/StartAndroidEmulatorTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.AdbProxy; 4 | import com.quittle.androidemulator.EmulatorConfiguration; 5 | import org.apache.commons.io.IOUtils; 6 | import org.gradle.api.DefaultTask; 7 | import org.gradle.api.GradleException; 8 | import org.gradle.api.logging.Logger; 9 | import org.gradle.api.tasks.TaskAction; 10 | 11 | import javax.inject.Inject; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.nio.charset.StandardCharsets; 15 | import java.util.ArrayList; 16 | import java.util.Arrays; 17 | import java.util.List; 18 | import java.util.Set; 19 | import java.util.concurrent.atomic.AtomicReference; 20 | import java.util.function.UnaryOperator; 21 | import java.util.regex.Matcher; 22 | import java.util.regex.Pattern; 23 | import java.util.stream.Collectors; 24 | import java.util.stream.Stream; 25 | 26 | public class StartAndroidEmulatorTask extends DefaultTask { 27 | /** 28 | * This is matching adb output lines. These emulator serial formats may change in the future and may lead to 29 | * breakages. Example ADB Output 30 | *
{@code
 31 |      * List of devices attached
 32 |      * emulator-5554       device
 33 |      * 192.168.1.2:42839   device
 34 |      * }
35 | */ 36 | private static final Pattern ADB_OUTPUT_EMULATOR_PATTERN = Pattern.compile("(emulator-(\\d{1,5}))\\s+device"); 37 | 38 | private final EmulatorConfiguration emulatorConfiguration; 39 | private final AdbProxy adbProxy; 40 | private final AtomicReference emulatorProcess; 41 | private final AtomicReference waitForDeviceProcess; 42 | 43 | @Inject 44 | public StartAndroidEmulatorTask( 45 | final EmulatorConfiguration emulatorConfiguration, 46 | final AdbProxy adbProxy, 47 | final AtomicReference emulatorProcess, 48 | final AtomicReference waitForDeviceProcess) { 49 | this.emulatorConfiguration = emulatorConfiguration; 50 | this.adbProxy = adbProxy; 51 | this.emulatorProcess = emulatorProcess; 52 | this.waitForDeviceProcess = waitForDeviceProcess; 53 | } 54 | 55 | @TaskAction 56 | public void act() { 57 | final boolean logEmulatorOutput = emulatorConfiguration.getLogEmulatorOutput(); 58 | 59 | final int proposedEmulatorPort = findAcceptableEmulatorPort(adbProxy); 60 | emulatorConfiguration.setEmulatorPort(proposedEmulatorPort); 61 | 62 | final List command = new ArrayList<>(); 63 | command.add(emulatorConfiguration.getEmulator().getAbsolutePath()); 64 | command.add("@" + emulatorConfiguration.getEmulatorName()); 65 | 66 | // Allows the plugin to monitor the logs from the emulator and start the emulator synchronously. Without this, 67 | // the emulator would be detached from the process being build and be much more difficult to shut down. 68 | command.add("-shell"); 69 | 70 | // Adds the port the emulator should start on. This is specified to enable targeting via ADB commands. 71 | command.add("-port"); 72 | command.add(String.valueOf(proposedEmulatorPort)); 73 | 74 | // User-specified arguments 75 | command.addAll(emulatorConfiguration.getAdditionalEmulatorArguments()); 76 | 77 | final ProcessBuilder pb = new ProcessBuilder(command.toArray(new String[0])); 78 | pb.environment().putAll(emulatorConfiguration.getEnvironmentVariableMap()); 79 | if (!logEmulatorOutput) { 80 | pb.inheritIO(); 81 | } 82 | 83 | final Logger logger = getLogger(); 84 | logger.debug("Starting emulator with command {} {}", pb.environment(), pb.command()); 85 | try { 86 | final Process directProcess = pb.start(); 87 | emulatorProcess.set(directProcess); 88 | if (logEmulatorOutput) { 89 | logOutput(directProcess, logger); 90 | } 91 | new Thread(() -> { 92 | final int returnCode; 93 | try { 94 | returnCode = directProcess.waitFor(); 95 | } catch (InterruptedException e) { 96 | logger.warn("Interrupted while watching emulator process", e); 97 | // Do nothing 98 | return; 99 | } 100 | 101 | if (returnCode != 0) { 102 | logger.error("Emulator exited abnormally with return code " + returnCode); 103 | final Process p = waitForDeviceProcess.get(); 104 | if (p != null) { 105 | p.destroyForcibly(); 106 | } 107 | } 108 | }).start(); 109 | Runtime.getRuntime().addShutdownHook(new Thread(() -> 110 | emulatorProcess.getAndUpdate(new ProcessDestroyer(getProject())))); 111 | } catch (final IOException e) { 112 | throw new RuntimeException("Emulator failed to start successfully", e); 113 | } 114 | } 115 | 116 | /** 117 | * Logs emulator output via new threads. 118 | * 119 | * @param process The process to log the output of 120 | * @param logger The logger to report output with 121 | */ 122 | private static void logOutput(final Process process, final Logger logger) { 123 | final InputStream stdout = process.getInputStream(); // NOPMD - These can't be closed outside of the thread 124 | final InputStream stderr = process.getErrorStream(); // NOPMD - These can't be closed outside of the thread 125 | new Thread(() -> { 126 | try (final InputStream stream = stdout) { 127 | IOUtils.lineIterator(stream, StandardCharsets.UTF_8).forEachRemaining(s -> logger.info("[Android Emulator - STDOUT] " + s)); 128 | } catch (IOException | IllegalStateException e) { 129 | logger.error("Error reading Android emulator stdout", e); 130 | } 131 | }).start(); 132 | new Thread(() -> { 133 | try (final InputStream stream = stderr) { 134 | IOUtils.lineIterator(stream, StandardCharsets.UTF_8).forEachRemaining(s -> logger.info("[Android Emulator - STDERR] " + s)); 135 | } catch (IOException | IllegalStateException e) { 136 | logger.error("Error reading Android emulator stderr", e); 137 | } 138 | }).start(); 139 | } 140 | 141 | private static int findAcceptableEmulatorPort(final AdbProxy adbProxy) { 142 | final Set reservedPorts = 143 | Stream.of(adbProxy.execute("devices")) 144 | .map(ADB_OUTPUT_EMULATOR_PATTERN::matcher) 145 | .filter(Matcher::matches) 146 | .map(matcher -> Integer.parseInt(matcher.group(2))) 147 | .collect(Collectors.toSet()); 148 | 149 | // Start at the top of the range and iterate down to increase the likelihood of getting an earlier match. 150 | for (int port = 5680; port >= 5554; port -= 2) { 151 | if (!reservedPorts.contains(port)) { 152 | return port; 153 | } 154 | } 155 | 156 | throw new GradleException("No viable emulator ports found"); 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/StopAndroidEmulatorTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import org.gradle.api.DefaultTask; 4 | import org.gradle.api.tasks.TaskAction; 5 | import org.gradle.api.tasks.TaskExecutionException; 6 | 7 | import javax.inject.Inject; 8 | import java.util.concurrent.TimeUnit; 9 | import java.util.concurrent.atomic.AtomicReference; 10 | import java.util.function.UnaryOperator; 11 | 12 | public class StopAndroidEmulatorTask extends DefaultTask { 13 | final AtomicReference emulatorProcess; 14 | 15 | @Inject 16 | public StopAndroidEmulatorTask(final AtomicReference emulatorProcess) { 17 | this.emulatorProcess = emulatorProcess; 18 | } 19 | 20 | @TaskAction 21 | public void act() { 22 | emulatorProcess.getAndUpdate(new ProcessDestroyer(getProject())); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/main/java/com/quittle/androidemulator/task/WaitForAndroidEmulatorTask.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator.task; 2 | 3 | import com.quittle.androidemulator.EmulatorConfiguration; 4 | import org.gradle.api.DefaultTask; 5 | import org.gradle.api.tasks.TaskAction; 6 | 7 | import javax.inject.Inject; 8 | import java.io.IOException; 9 | import java.util.Arrays; 10 | import java.util.List; 11 | import java.util.concurrent.atomic.AtomicReference; 12 | 13 | public class WaitForAndroidEmulatorTask extends DefaultTask { 14 | private final EmulatorConfiguration emulatorConfiguration; 15 | private final AtomicReference waitForDeviceProcess; 16 | 17 | @Inject 18 | public WaitForAndroidEmulatorTask(final EmulatorConfiguration emulatorConfiguration, final AtomicReference waitForDeviceProcess) { 19 | this.emulatorConfiguration = emulatorConfiguration; 20 | this.waitForDeviceProcess = waitForDeviceProcess; 21 | } 22 | 23 | @TaskAction 24 | public void act() { 25 | // The AdbProxy cannot be used here as the process needs to run asynchronously in order for it to be 26 | // terminable if the Gradle run is aborted early. 27 | final List command = Arrays.asList( 28 | emulatorConfiguration.getAdb().getAbsolutePath(), 29 | "-s", "emulator-" + emulatorConfiguration.getEmulatorPort(), 30 | "wait-for-device", 31 | "shell", 32 | "while $(exit $(getprop sys.boot_completed)) ; do sleep 1; done;"); 33 | final ProcessBuilder pb = new ProcessBuilder(command.toArray(new String[0])); 34 | pb.environment().putAll(emulatorConfiguration.getEnvironmentVariableMap()); 35 | try { 36 | final Process p = pb.start(); 37 | waitForDeviceProcess.set(p); 38 | p.waitFor(); 39 | } catch (IOException | InterruptedException e) { 40 | throw new RuntimeException("Unable to wait for emulator", e); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/test/java/com/quittle/androidemulator/ArchitectureUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import java.util.Arrays; 4 | import java.util.Set; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.params.ParameterizedTest; 10 | import org.junit.jupiter.params.provider.EnumSource; 11 | 12 | import static org.junit.jupiter.api.Assertions.*; 13 | 14 | class ArchitectureUtilsTest { 15 | @ParameterizedTest 16 | @EnumSource(ArchitectureUtils.Architecture.class) 17 | public void testArchitecturesValid(ArchitectureUtils.Architecture architecture) { 18 | assertTrue(architecture.allValues.contains(architecture.emulatorArchitecture)); 19 | 20 | final Set otherArchitectures = Stream.of(ArchitectureUtils.Architecture.values()) 21 | .filter(otherArchitecture -> otherArchitecture != architecture) 22 | .flatMap(otherArchitecture -> otherArchitecture.allValues.stream()) 23 | .collect(Collectors.toUnmodifiableSet()); 24 | for (final String abi : architecture.allValues) { 25 | assertFalse(otherArchitectures.contains(abi)); 26 | } 27 | } 28 | 29 | @Test 30 | public void testGetEmulatorAbiString() { 31 | final String abi = ArchitectureUtils.getEmulatorAbiString(); 32 | assertNotNull(abi); 33 | final Set allAbis = Stream.of(ArchitectureUtils.Architecture.values()) 34 | .flatMap(architecture -> architecture.allValues.stream()).collect(Collectors.toUnmodifiableSet()); 35 | assertTrue(allAbis.contains(abi)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/test/java/com/quittle/androidemulator/CollectionUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | import static com.quittle.androidemulator.CollectionUtils.mutableListOf; 10 | import static org.junit.jupiter.api.Assertions.*; 11 | 12 | class CollectionUtilsTest { 13 | @Test 14 | public void testMutableListOf() { 15 | assertEquals(Collections.emptyList(), mutableListOf()); 16 | 17 | final List list = mutableListOf(1, 2, 3); 18 | assertEquals(Arrays.asList(1, 2, 3), list); 19 | assertDoesNotThrow(() -> list.add(4)); 20 | assertEquals(Arrays.asList(1, 2, 3, 4), list); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/test/java/com/quittle/androidemulator/EmulatorConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import com.android.build.gradle.BaseExtension; 4 | import com.android.build.gradle.internal.dsl.DefaultConfig; 5 | import io.mockk.impl.annotations.MockK; 6 | import io.mockk.junit5.MockKExtension; 7 | import org.gradle.api.Project; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.condition.OS; 11 | import org.junit.jupiter.api.extension.ExtendWith; 12 | import org.junit.jupiter.api.io.TempDir; 13 | import org.mockito.Mock; 14 | import org.mockito.junit.jupiter.MockitoExtension; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | 19 | import static io.mockk.MockKKt.every; 20 | import static org.junit.jupiter.api.Assertions.*; 21 | import static org.mockito.Mockito.when; 22 | 23 | @SuppressWarnings({ "PMD.AvoidDuplicateLiterals" }) 24 | @ExtendWith({ MockitoExtension.class, MockKExtension.class }) 25 | class EmulatorConfigurationTest { 26 | @Mock 27 | private Project mockProject; 28 | @MockK 29 | private BaseExtension mockBaseExtension; 30 | @Mock 31 | private AndroidEmulatorExtension mockAndroidEmulatorExtension; 32 | @Mock 33 | private AndroidEmulatorExtension.EmulatorExtension mockEmulatorExtension; 34 | @Mock 35 | private DefaultConfig mockDefaultConfig; 36 | @TempDir 37 | File tempDir; 38 | 39 | private EmulatorConfiguration configuration; 40 | 41 | @BeforeEach 42 | void setUp() { 43 | every(_scope -> mockBaseExtension.getSdkDirectory()).returns(tempDir); 44 | every(_scope -> mockBaseExtension.getDefaultConfig()).returns(mockDefaultConfig); 45 | when(mockAndroidEmulatorExtension.getEmulator()).thenReturn(mockEmulatorExtension); 46 | configuration = new EmulatorConfiguration(mockProject, mockBaseExtension, mockAndroidEmulatorExtension); 47 | } 48 | 49 | @Test 50 | void testGetSdkManager_emptySdkRoot() { 51 | assertGetSdkManagerThrows(); 52 | } 53 | 54 | @Test 55 | void testGetSdkManager_unrelatedFolder() { 56 | makeSdkmanagerInTempDirectory("foo"); 57 | assertGetSdkManagerThrows(); 58 | } 59 | 60 | /** 61 | * Commandline tools downloaded standalone and placed in SDK_ROOT 62 | */ 63 | @Test 64 | void testGetSdkManager_cmdlineToolsTools() { 65 | final File file = makeSdkmanagerInTempDirectory("cmdline-tools", "tools", "bin"); 66 | assertEquals(file, configuration.getSdkManager()); 67 | } 68 | 69 | /** 70 | * Commandline tools installed by sdkmanager installed as "latest" version 71 | */ 72 | @Test 73 | void testGetSdkManager_cmdlineToolsLatest() { 74 | final File file = makeSdkmanagerInTempDirectory("cmdline-tools", "latest", "bin"); 75 | assertEquals(file, configuration.getSdkManager()); 76 | } 77 | 78 | /** 79 | * Commandline tools installed by sdkmanager installed as a specific version 80 | */ 81 | @Test 82 | void testGetSdkManager_cmdlineToolsVersion() { 83 | final File file = makeSdkmanagerInTempDirectory("cmdline-tools", "2.1", "bin"); 84 | assertEquals(file, configuration.getSdkManager()); 85 | } 86 | 87 | /** 88 | * Usecase for original sdk tools 89 | */ 90 | @Test 91 | void testGetSdkManager_tools() { 92 | final File file = makeSdkmanagerInTempDirectory("tools", "bin"); 93 | assertEquals(file, configuration.getSdkManager()); 94 | } 95 | 96 | @Test 97 | void testGetSdkManager_allowInvalidVersions() { 98 | File sdkmanager = makeSdkmanagerInTempDirectory("cmdline-tools", "madeupversion", "bin"); 99 | assertEquals(sdkmanager, configuration.getSdkManager()); 100 | } 101 | 102 | @Test 103 | void testGetSdkManager_preferValidVersions() { 104 | // Despite having many options for versions, only the valid version should be 105 | // chosen 106 | makeSdkmanagerInTempDirectory("cmdline-tools", "invalid", "bin"); 107 | makeSdkmanagerInTempDirectory("cmdline-tools", "0invalid", "bin"); 108 | makeSdkmanagerInTempDirectory("cmdline-tools", "1invalid", "bin"); 109 | makeSdkmanagerInTempDirectory("cmdline-tools", "1.invalid", "bin"); 110 | makeSdkmanagerInTempDirectory("cmdline-tools", "1-tagged", "bin"); 111 | final File sdkmanager = makeSdkmanagerInTempDirectory("cmdline-tools", "1.0", "bin"); 112 | makeSdkmanagerInTempDirectory("cmdline-tools", "2invalid", "bin"); 113 | 114 | assertEquals(sdkmanager, configuration.getSdkManager()); 115 | } 116 | 117 | @Test 118 | void testGetSdkManager_versionOrderOfPrecedense() { 119 | final File version1 = makeSdkmanagerInTempDirectory("cmdline-tools", "1", "bin"); 120 | final File version2 = makeSdkmanagerInTempDirectory("cmdline-tools", "2.1", "bin"); 121 | final File version3 = makeSdkmanagerInTempDirectory("cmdline-tools", "3", "bin"); 122 | final File version10 = makeSdkmanagerInTempDirectory("cmdline-tools", "10.0.1", "bin"); 123 | 124 | // Verify their precedence by deleting them in order 125 | assertEquals(version10, configuration.getSdkManager()); 126 | deleteFile(version10); 127 | assertEquals(version3, configuration.getSdkManager()); 128 | deleteFile(version3); 129 | assertEquals(version2, configuration.getSdkManager()); 130 | deleteFile(version2); 131 | assertEquals(version1, configuration.getSdkManager()); 132 | deleteFile(version1); 133 | assertGetSdkManagerThrows(); 134 | } 135 | 136 | @Test 137 | void testGetSdkManager_orderOfVersionPrecedence() { 138 | // These should each override eachotehr 139 | final File cmdlineTools = makeSdkmanagerInTempDirectory("cmdline-tools", "tools", "bin"); 140 | final File cmdlineLatest = makeSdkmanagerInTempDirectory("cmdline-tools", "latest", "bin"); 141 | final File cmdlineVersion = makeSdkmanagerInTempDirectory("cmdline-tools", "2.1", "bin"); 142 | final File legacy = makeSdkmanagerInTempDirectory("tools", "bin"); 143 | 144 | // Verify their precedence by deleting them in order 145 | assertEquals(cmdlineTools, configuration.getSdkManager()); 146 | deleteFile(cmdlineTools); 147 | 148 | assertEquals(cmdlineLatest, configuration.getSdkManager()); 149 | deleteFile(cmdlineLatest); 150 | 151 | assertEquals(cmdlineVersion, configuration.getSdkManager()); 152 | deleteFile(cmdlineVersion); 153 | 154 | assertEquals(legacy, configuration.getSdkManager()); 155 | deleteFile(legacy); 156 | 157 | assertGetSdkManagerThrows(); 158 | } 159 | 160 | /** 161 | * Asserts that calling {@link EmulatorConfiguration#getSdkManager()} throws an 162 | * exception. 163 | */ 164 | private void assertGetSdkManagerThrows() { 165 | final RuntimeException exception = assertThrows(RuntimeException.class, () -> configuration.getSdkManager()); 166 | assertEquals("Unable to find a valid sdkmanager to use.", exception.getMessage()); 167 | } 168 | 169 | /** 170 | * Given a folder path, generates a synthetic {@code sdkmanager} relative to 171 | */ 172 | private File makeSdkmanagerInTempDirectory(String... path) { 173 | final File parentFile = new File(tempDir, String.join(File.separator, path)); 174 | assertTrue(parentFile.mkdirs()); 175 | final File sdkmanager = new File(parentFile, OS.WINDOWS.isCurrentOs() ? "sdkmanager.bat" : "sdkmanager"); 176 | try { 177 | assertTrue(sdkmanager.createNewFile()); 178 | return sdkmanager; 179 | } catch (final IOException e) { 180 | throw new RuntimeException(e); 181 | } 182 | } 183 | 184 | /** 185 | * Deletes a file and its parent directories recursively. Deletes up the tree as 186 | * long as there are no other children. 187 | * 188 | * @param file The file to delete 189 | */ 190 | private static void deleteFile(final File file) { 191 | assertTrue(file.delete()); 192 | final File parent = file.getParentFile(); 193 | if (parent != null) { 194 | final String[] children = parent.list(); 195 | if (children != null && children.length == 0) { 196 | deleteFile(parent); 197 | } 198 | } 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /android-emulator-plugin/src/test/java/com/quittle/androidemulator/VersionComparatorTest.java: -------------------------------------------------------------------------------- 1 | package com.quittle.androidemulator; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.Comparator; 6 | 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class VersionComparatorTest { 10 | @Test 11 | void testCompare() { 12 | final Comparator comparator = new VersionComparator(); 13 | 14 | assertEquals(comparator.compare("1.2.3", "1.2.3.4"), -1); 15 | assertEquals(comparator.compare("1.2.4", "1.2.3.4"), 1); 16 | assertEquals(comparator.compare("1.2.4", "1"), 1); 17 | assertEquals(comparator.compare("1.2.3", "1.3.0"), -1); 18 | assertEquals(comparator.compare("1.2", "1.2"), 0); 19 | } 20 | 21 | @Test 22 | void testCompareInvalid() { 23 | final Comparator comparator = new VersionComparator(); 24 | 25 | assertEquals(comparator.compare("1.invalid", "1.2"), -1); 26 | assertEquals(comparator.compare("invalid", "1.3"), -1); 27 | assertEquals(comparator.compare("1", "1.2.3.invalid"), 1); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /example-android-project/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | final Map env = System.getenv() 3 | project.ext.ANDROID_GRADLE_VERSION = env.getOrDefault('ANDROID_GRADLE_VERSION', '7.0.0') 4 | project.ext.ANDROID_EMULATOR_SDK_VERSION = Integer.valueOf(env.getOrDefault('ANDROID_EMULATOR_SDK_VERSION', '21')) 5 | project.ext.ANDROID_EMULATOR_GOOGLE_APIS = Boolean.valueOf(env.getOrDefault('ANDROID_EMULATOR_GOOGLE_APIS', 'false')) 6 | project.ext.ANDROID_EMULATOR_ABI = env.getOrDefault('ANDROID_EMULATOR_ABI', 'x86') 7 | project.ext.ENABLE_FOR_ANDROID_TESTS = Boolean.valueOf(env.getOrDefault('ENABLE_FOR_ANDROID_TESTS', 'true')) 8 | project.ext.LOG_ANDROID_EMULATOR = Boolean.valueOf(env.getOrDefault('LOG_ANDROID_EMULATOR', 'false')) 9 | project.ext.FAIL_EMULATOR_STARTUP = Boolean.valueOf(env.getOrDefault('FAIL_EMULATOR_STARTUP', 'false')) 10 | project.ext.ANDROID_EMULATOR_DEVICE = env.getOrDefault('ANDROID_EMULATOR_DEVICE', null) 11 | 12 | repositories { 13 | mavenLocal() 14 | google() 15 | jcenter() 16 | } 17 | 18 | dependencies { 19 | classpath 'com.quittle:android-emulator:+' 20 | classpath "com.android.tools.build:gradle:${ANDROID_GRADLE_VERSION}" 21 | } 22 | } 23 | 24 | plugins { 25 | id 'com.quittle.setup-android-sdk' version '2.0.3' 26 | } 27 | 28 | apply plugin: 'com.android.application' 29 | apply plugin: 'com.quittle.android-emulator' 30 | 31 | allprojects { 32 | repositories { 33 | google() 34 | jcenter() 35 | } 36 | } 37 | 38 | android { 39 | compileSdkVersion 29 40 | buildToolsVersion '29.0.3' 41 | 42 | defaultConfig { 43 | minSdkVersion 14 44 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 45 | } 46 | 47 | testOptions { 48 | execution 'ANDROIDX_TEST_ORCHESTRATOR' 49 | } 50 | 51 | useLibrary 'android.test.runner' 52 | } 53 | 54 | dependencies { 55 | androidTestImplementation 'androidx.test:runner:1.3.0' 56 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 57 | androidTestUtil 'androidx.test:orchestrator:1.3.0' 58 | } 59 | 60 | androidEmulator { 61 | emulator { 62 | sdkVersion ANDROID_EMULATOR_SDK_VERSION 63 | sdkVersion = ANDROID_EMULATOR_SDK_VERSION 64 | 65 | abi ANDROID_EMULATOR_ABI 66 | abi = ANDROID_EMULATOR_ABI 67 | 68 | includeGoogleApis ANDROID_EMULATOR_GOOGLE_APIS 69 | includeGoogleApis = ANDROID_EMULATOR_GOOGLE_APIS 70 | 71 | device ANDROID_EMULATOR_DEVICE 72 | device = ANDROID_EMULATOR_DEVICE 73 | } 74 | 75 | enableForAndroidTests ENABLE_FOR_ANDROID_TESTS 76 | enableForAndroidTests = ENABLE_FOR_ANDROID_TESTS 77 | 78 | headless true 79 | headless = true 80 | 81 | additionalEmulatorArguments '-show-kernel', '-verbose' 82 | additionalEmulatorArguments = ['-show-kernel', '-verbose'] 83 | 84 | if (FAIL_EMULATOR_STARTUP) { 85 | additionalEmulatorArguments = ['fake', 'arguments'] 86 | } 87 | 88 | logEmulatorOutput LOG_ANDROID_EMULATOR 89 | logEmulatorOutput = LOG_ANDROID_EMULATOR 90 | } 91 | 92 | com.android.ddmlib.DdmPreferences.setTimeOut(30000) 93 | -------------------------------------------------------------------------------- /example-android-project/gradle.properties: -------------------------------------------------------------------------------- 1 | android.useAndroidX=true 2 | -------------------------------------------------------------------------------- /example-android-project/src/androidTest/java/ExampleInstrumentationTest.java: -------------------------------------------------------------------------------- 1 | import androidx.test.ext.junit.runners.AndroidJUnit4; 2 | import org.junit.Test; 3 | import org.junit.runner.RunWith; 4 | 5 | @RunWith(AndroidJUnit4.class) 6 | public class ExampleInstrumentationTest { 7 | 8 | @Test 9 | public void example() {} 10 | } 11 | -------------------------------------------------------------------------------- /example-android-project/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quittle/gradle-android-emulator/949ccb7957c5956738c27d87b900312809b87006/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /validate_plugin: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Validate that the plugin works correctly. 4 | 5 | set -e 6 | 7 | TARGET="$1" 8 | 9 | # Checks if the target passed in matches the first argument. If no argument is given, then all targets should run 10 | function should_run_target() { 11 | name="$1" 12 | 13 | if [[ "${TARGET}" -eq "${name}" || -z "${TARGET}" ]]; then 14 | return 0 15 | else 16 | return 1 17 | fi 18 | } 19 | 20 | function kill_emulator() { 21 | pkill emulator || true 22 | pkill emulator64-arm || true 23 | pkill emulator64-x86 || true 24 | rm -f ./example-android-project/build/android-avd-root/*/*.lock 25 | } 26 | 27 | # Clean up possibly existing files to ensure a fresh start 28 | rm -f 'example-android-project/local.properties' 29 | rm -rf 'example-android-project/build' 30 | rm -rf 'android-emulator-plugin/build' 31 | 32 | # Plugin locally to be consumed by example project 33 | ./gradlew -p android-emulator-plugin publishToMavenLocal 34 | 35 | # ADB install may take longer than normal in CI due to potentially low-power machines 36 | export ADB_INSTALL_TIMEOUT=10 37 | 38 | # Add additional gradle options for testing 39 | export GRADLE_OPTS="${GRADLE_OPTS} -Dorg.gradle.logging.level=info" 40 | 41 | # Run the test on the default (for the project) emulator as well as using an older SDK version 42 | # Run one after the other to ensure the plugin handles changing of configuration. 43 | if should_run_target 1; then 44 | ./gradlew -p example-android-project connectedCheck 45 | kill_emulator 46 | ANDROID_EMULATOR_SDK_VERSION=21 ./gradlew -p example-android-project connectedCheck 47 | fi 48 | 49 | # Use a google_apis flavor 50 | if should_run_target 2; then 51 | ANDROID_EMULATOR_SDK_VERSION=24 ANDROID_EMULATOR_GOOGLE_APIS=true ./gradlew -p example-android-project connectedCheck 52 | fi 53 | 54 | # Validate that the emulator is needed or the tests would fail due to a lack of devices 55 | if should_run_target 3; then 56 | ENABLE_FOR_ANDROID_TESTS=false ./gradlew -p example-android-project connectedCheck && 57 | echo 'Build should not have succeeded' && exit 1 || 58 | echo 'Build failure expected due to "No connected devices!"' 59 | fi 60 | 61 | # Use a newer version of Gradle plugin 62 | if should_run_target 4; then 63 | ANDROID_GRADLE_VERSION=7.1.0 ANDROID_EMULATOR_GOOGLE_APIS=true ANDROID_EMULATOR_SDK_VERSION=24 ./gradlew -p example-android-project connectedCheck 64 | fi 65 | 66 | # Use the logEmulatorOutput flag 67 | if should_run_target 5; then 68 | LOG_ANDROID_EMULATOR=true ANDROID_EMULATOR_SDK_VERSION=24 ANDROID_EMULATOR_GOOGLE_APIS=true ./gradlew -p example-android-project connectedCheck 69 | fi 70 | 71 | # Use the failed emulator starts don't hang forever 72 | if should_run_target 6; then 73 | FAIL_EMULATOR_STARTUP=true ./gradlew -p example-android-project assemble # Prove the flag doesn't fail the build 74 | FAIL_EMULATOR_STARTUP=true ./gradlew -p example-android-project connectedCheck && 75 | echo 'Build should not have succeeded' && exit 1 || 76 | echo 'Build failure expected due to invalid emulator arguments' 77 | fi 78 | 79 | # Use the emulator's device field by specifying the device type 80 | if should_run_target 7; then 81 | ANDROID_EMULATOR_SDK_VERSION=24 ANDROID_EMULATOR_DEVICE=pixel_xl ./gradlew -p example-android-project connectedCheck 82 | fi 83 | 84 | # Use the device field by specifying the device code 85 | if should_run_target 8; then 86 | ANDROID_EMULATOR_SDK_VERSION=24 ANDROID_EMULATOR_DEVICE=19 ./gradlew -p example-android-project connectedCheck 87 | fi 88 | 89 | # Use the latest Gradle plugin 90 | if should_run_target 9; then 91 | ANDROID_GRADLE_VERSION=7.3.0 ANDROID_EMULATOR_GOOGLE_APIS=true ANDROID_EMULATOR_SDK_VERSION=24 ./gradlew -p example-android-project connectedCheck 92 | fi 93 | --------------------------------------------------------------------------------