android – How to execute a task on emulators by launching them sequentially with one command?


Created a number of emulators through Android Studio . The task is the following:

  1. Launch first emulator
  2. Run Autotests
  3. close emulator
  4. Repeat steps 1-3 on the required number of emulators (there may be 20)

For the whole task while using one command.

Created the following gradle tasks:

def sdkDir = ".../Android/sdk/"

task runEmulator1(type: Exec) {
    group = "custom"

    String[] command = [sdkDir + "tools/emulator.exe", '-avd', 'Nexus_5X_Android_8.0'];
    commandLine command

task runEmulator2(type: Exec) {
    group = "custom"

    String[] command = [sdkDir + "tools/emulator.exe", '-avd', 'Nexus_S_Android_5.1'];
    commandLine command

task closeEmulator(type: Exec) {
    group = "custom"

    def command = ['adb', 'emu', 'kill']
    commandLine command

And I try to solve the problem with the command:

./gradlew runEmulator1 connectedCheck closeEmulator runEmulator2 connectedCheck closeEmulator

But after starting the first emulator, the first task does not finish and the second one does not start. If used starting from connectedCheck , then tasks are executed correctly (until runEmulator2 )

I also tried to run the following task:

task runEmulator1Process  {
    group = "custom"

    String[] aCommand = [sdkDir + "tools/emulator.exe", '-avd', 'Nexus_5X_Android_8.0'];
    try {
        Process process = new ProcessBuilder(aCommand).start();
        process.waitFor(5, TimeUnit.SECONDS);
    } catch (Exception e) {

But in this case, the emulator starts even when the project is compiled.

How to achieve the desired result?


I suspect that your problem lies in the fact that the emulator does not start immediately after the execution of emulator.exe . It needs time to initialize, etc.
If you wait for its real start, then everything can work out.

You can get some inspiration by rummaging through the Jenkins plugin sources:

There they have the same problem solved: start the emulator, wait for it, and only then to the next. task.

I'm sorry, at first I did not understand the whole essence of the problem.
It looks like Gragle is always waiting for the external command to complete, you can run it asynchronously with something like this self-written:

As a simpler option, you can try to write your own .bat file for each emulator like

start <sdkDir>/tools/emulator.exe -avd Nexus_5X_Android_8.0

And run it from Gradle. The bottom line is that cmd runs an external command and exits, then Gradle tasks will not "hang".

Scroll to Top