有没有一种编程方法可以获取连接到adb的安卓设备列表?
我想在桌面应用程序中使用Java来实现。我已经获得了adb.exe的路径,但对"adb devices"响应进行解析似乎不是最好的方法。
是否有更可靠的方法?
有没有一种编程方法可以获取连接到adb的安卓设备列表?
我想在桌面应用程序中使用Java来实现。我已经获得了adb.exe的路径,但对"adb devices"响应进行解析似乎不是最好的方法。
是否有更可靠的方法?
这是我完成它的方法
try {
Process process = Runtime.getRuntime().exec("adb devices");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
Pattern pattern = Pattern.compile("^([a-zA-Z0-9\\-]+)(\\s+)(device)");
Matcher matcher;
while ((line = in.readLine()) != null) {
if (line.matches(pattern.pattern())) {
matcher = pattern.matcher(line);
if (matcher.find())
System.out.println(matcher.group(1));
}
}
} catch (IOException e) {
e.printStackTrace();
}
最佳方案取决于您要如何使用列表。如果您要在找到的设备上运行一些adb命令,请解析adb devices
输出是明显的选择。另一个选项是通过USB堆栈并收集带有ADB接口枚举的设备的序列号。或者我的最爱-在Linux下,我只需创建一个自定义的udev
规则,跟踪所有连接的ADB设备。我的使用数据库,但它可以像为每个ADB设备创建符号链接然后检查文件列表那样简单。
对于那些寻找 Kotlin 解决方案的人,我已经改编了 Buda Florin 的答案:
class Cli {
fun runCommand(cmd: String, workingDir: File = File("."), timeout: Duration = 3.minutes): String? {
// this is modified from https://dev59.com/ZFsW5IYBdhLWcg3wFT2n#52441962
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
}
}