Tuesday, January 3, 2017

Gradle task for launching Android simulator

Android build toolchain, albeit being powerful, sometimes lacks some essential functionality required for the modern software development. In particular, running instrumented unit-tests in the CI environment: those tests require a device or a simulator running, however developers need some scripting to make it work.

To simplify the task, I've created a Gradle task that verifies if any Android device or simulator is connected. If not, the task launches a simulator with the first AVD in the list (or fails if no AVDs are found). It's up to you to make the dependencies for the connectedCheck task. The sample output:

> ./gradlew connect --info

...

:AndroidSampleApp:connect (Thread[main,5,main]) started.
:AndroidSampleApp:connect
Executing task ':AndroidSampleApp:connect' (up-to-date check took 0.001 secs) due to:
  Task has not declared any outputs.
Detecting devices...
Launching emulator for Nexus_5_API_25 ...
:AndroidSampleApp:connect (Thread[main,5,main]) completed. Took 14.186 secs.

BUILD SUCCESSFUL

The code (just add it into the build.gradle of the module):