Created
October 29, 2016 12:49
-
-
Save vincetreur/50c746abbffc90dc5a4fa9a7821272eb to your computer and use it in GitHub Desktop.
Sometimes you need to send adb commands to all connected devices/emulators from your gradle script. This function will do that for you. Create a closure that takes a serial id (string) as an argument and call sendToDevices().
This file contains hidden or 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
/* | |
Example: | |
task tapPowerButton() { | |
group = 'device' | |
description = 'Tap the power button on all devices/emulators' | |
doLast { | |
def action = { serial -> | |
def adb = android.getAdbExe().toString() | |
exec { | |
commandLine "$adb -s $serial shell input keyevent 26".split(' ') | |
} | |
} | |
sendToDevices(action) | |
} | |
} | |
*/ | |
/** | |
* Call closure for each connected device or emulator. | |
* Any exception thrown by the closure will be collected and the *first* one will be thrown | |
* once the closure has been called for all devices/emulators. | |
* @param closure the serialid | |
*/ | |
def sendToDevices(def closure) { | |
def adb = android.getAdbExe().toString() | |
def output = "${adb} devices".execute().text | |
Throwable caughtThrowable = null | |
output.eachLine { line -> | |
line = line.toLowerCase() | |
def processLine = line.contains("emulator") || (line.contains("device") && !line.contains("devices")) | |
if (processLine) { | |
def serial = line.split().first() | |
println("Calling closure with serial '${serial}'") | |
try { | |
closure(serial) | |
} catch (Throwable t) { | |
// Do not crash if we get an exception from one device | |
// Store the throwable so we can rethrow it at the end | |
if (caughtThrowable == null) { | |
caughtThrowable = t | |
} | |
t.printStackTrace() | |
} | |
} | |
} | |
if (caughtThrowable != null) { | |
throw caughtThrowable | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment