【发布时间】:2014-01-25 21:12:48
【问题描述】:
我想编写一个 java 程序来查找设备并列出其内容。为此,我首先通过 Java 的 Process 类触发“adb devices”并解析输出,它只适用于 finde。然后我想触发这个命令:
adb shell -s DEVICE-SERIAL /sdcard/
当我将它放入终端时,我得到了正确的输出,即 /sdcard/ 根目录下所有文件夹和文件的列表。
当我把它放到 Java 代码中时,什么都没有返回。然而,当您拼错 adb 命令时,Stderr 包含您获得的标准帮助页面。有趣的是:为了调试,我输出发送给 ADB 的每个命令。如果我运行我的程序并复制完全相同的生成命令并在我的终端中运行它,它就可以正常工作。
这是为什么呢?作为参考,这是我的代码摘录:
ADB.java:
public static String runShellCommand(Device d, String command) {
return runCommand(d, "shell " + command);
}
public static String runCommand(Device d, String command) {
Runtime runtime = Runtime.getRuntime();
String full = "";
String error = "";
try {
if (d != null) {
command = "-s " + d.getSerial() + " " + command;
}
System.out.println("Running command: adb " + command);
Process process = runtime.exec(new String[] {ADB_LOCATION, command});
process.waitFor();
BufferedReader stdin = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errin = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = stdin.readLine()) != null) {
full += line;
}
while ((line = errin.readLine()) != null) {
error += line;
}
if (!error.isEmpty()) {
System.err.println("\n=== ADB reports: ===");
System.err.println(error);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("App was overenthuasiastic. Couldn't wait for thread to finish.");
}
return full;
}
Device.java:
public ArrayList<Folder> getFoldersInDirectory(String dir) {
String[] list = ls(dir);
for (String s: list) {
System.out.println(s);
System.out.println(isFolderOrFile(dir + s));
}
// Just for debugging, gets completed once this runs.
return null;
}
protected String[] ls(String dir) {
String result = ADB.runShellCommand(this, "ls " + dir);
System.out.println(result);
return result.split("\n");
}
正如我之前所说,所有其他命令都运行良好(我测试了设备、get-state、get-serialno)。
输出:
【问题讨论】:
-
ADB.runShellCommand()在您的ADB.javasn-p 中丢失 -
runShellCommand 基本上只是调用 runCommand 并将“shell”放在它前面,但我会发布它。
标签: java android shell process adb