Skip to content

Instantly share code, notes, and snippets.

@nuald nuald/build.gradle
Created Jan 4, 2017

Embed
What would you like to do?
Gradle task for the verification that any Android device is connected and launching a simulator if not.
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
You can’t perform that action at this time.