For those looking for a Kotlin solution, I've adapted Buda Florin's answer:
class Cli {
fun runCommand(cmd: String, workingDir: File = File("."), timeout: Duration = 3.minutes): String? {
// this is modified from https://stackoverflow.com/a/52441962/940217
return try {
val parts = "\\s".toRegex().split(cmd)
val proc = ProcessBuilder(*parts.toTypedArray())
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
proc.waitFor(timeout.inWholeSeconds, TimeUnit.SECONDS)
proc.inputStream.bufferedReader().readText()
} catch (e: IOException) {
e.printStackTrace()
null
}
}
}
class AdbUtils(){
fun listDevices(): List<String>? {
val c = Cli()
val adbDevicesResponse :String? = c.runCommand("adb devices")
var deviceIds = adbDevicesResponse?.lines()?.mapNotNull {
val matches = """^([a-zA-Z0-9\-]+)(\s+)(device)""".toRegex().find(it)
matches?.groupValues?.get(1)
}
return deviceIds
}
}