Created
January 4, 2017 07:24
-
-
Save nuald/6b0408cf23039631b7db76347d405419 to your computer and use it in GitHub Desktop.
Gradle task for the verification that any Android device is connected and launching a simulator if not.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apply plugin: 'com.android.application' | |
task connect(type: ConnectDevicesTask) { | |
description 'Verifies that any Android device is connected and runs a simulator if not.' | |
} | |
import com.android.ddmlib.AndroidDebugBridge | |
import com.android.ddmlib.IDevice | |
import org.gradle.tooling.BuildException | |
class ConnectDevicesTask extends DefaultTask { | |
@TaskAction | |
void connect() { | |
project.logger.info "Detecting devices..." | |
AndroidDebugBridge.initIfNeeded false /*clientSupport*/ | |
AndroidDebugBridge bridge = AndroidDebugBridge.createBridge( | |
project.android.adbExe.absolutePath, | |
false /*forceNewBridge*/ | |
) | |
long timeOut = 30000 // 30 sec | |
int sleepTime = 1000 | |
while (!bridge.hasInitialDeviceList() && timeOut > 0) { | |
sleep sleepTime | |
timeOut -= sleepTime | |
} | |
if (timeOut <= 0 && !bridge.hasInitialDeviceList) { | |
throw new BuildException("Timeout getting device list.", null) | |
} | |
IDevice[] devices = bridge.devices | |
if (devices.length == 0) { | |
String emulator = project.android.sdkDirectory.absolutePath + "/tools/emulator" | |
String command = "$emulator -list-avds" | |
String avds = command.execute().text | |
if (avds?.trim()) { | |
String avd = avds.split()[0] | |
String runCmd = "$emulator -avd $avd" | |
project.logger.info "Launching emulator for $avd ..." | |
runCmd.execute() | |
timeOut = 30000 // 30 sec | |
while (bridge.devices.length == 0 && timeOut > 0) { | |
sleep sleepTime | |
timeOut -= sleepTime | |
} | |
if (bridge.devices.length == 0 && timeOut <= 0) { | |
throw new BuildException("Timeout launching the emulator.", null) | |
} | |
} else { | |
throw new BuildException("No registered AVDs!", null) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment