Executing commands from Gradle

Simply invoke command line processes within Gradle Tasks

Executing commands from Gradle

Recently, I setup a system to automate the process of taking screenshots of an Android application. The system consisted of instrumentation tests, Gradle tasks, and a Fastlane command. The instrumentation tests were responsible for loading the different screens and capturing the screenshots. The Gradle tasks were responsible for running these tests, toggling Demo Mode for the device, and copying over the screenshots from the device to the local machine. Finally, the Fastlane command wired everything together and reported the results back to a communication channel.

Creating this automation required calling command line processes from within Gradle tasks. Specifically, I had to call ADB commands to setup Demo Mode on a device. A Gradle task calling command line processes turned out to be fairly simple to implement, but not necessarily obvious, so I figured I'd share.

Gradle provides the ability to call command line processes with the Exec class. The following is an example to setup Demo Mode on device by calling the appropriate ADB commands from a Gradle task:

Kotlin

task("enterDemoMode", Exec::class) {
    group = "demoMode"

    executable = "adp"
    args = listOf("shell", "settings", "put", "global", "sysui_demo_allowed", "1")
}

Groovy

task('enterDemoMode', type: Exec, group: 'demoMode') {
    executable 'adb'
    args 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', '1'
}

The Gradle task is created using the task function. In both the Kotlin and Groovy versions, the name ("enterDemoMode") and type ( Exec::class ) are provided, however, the Kotlin version specifies the type as a class ( Exec::class ) and the Groovy version specifies just the class name ( Exec ). The Groovy version provides the group that this task belongs to as a parameter in the function, whereas, the Kotlin version provides the group within the lambda.

Both the Kotlin and Groovy versions of the tasks specify the executable and args within the lambda closure. Obviously, the executable property states the command line process that is going to be invoked. And the args provides the command line process with a list of arguments.

The above tasks equates to running the following command in your terminal:

adb shell settings put global sysui_demo_allowed 1

End

Executing command line processes from within Gradle tasks is fairly straightforward and provides a powerful toolset for automation.