I want to write a java program to find a device and list its contents. For that I first fire "adb devices" via Java's Process class and parse the output, which works just finde. Then I want to fire this command:
adb shell -s DEVICE-SERIAL /sdcard/
When I put that into my terminal I get the right output, a list of all folders and files in at the root of /sdcard/.
When I put that into Java code nothing is returned. Stderr however contains the standard help page you get when you misspell an adb command. Here's the funny thing: For debugging I output every command sent to ADB. If I run my programm and copy the exact same generated command and run it in my terminal it works just fine.
Why is that? For reference, here are my code excerpts for that:
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");
}
As I said before, every other command runs just fine (I tested devices, get-state, get-serialno).
Outputs:
ADB.runShellCommand()
is missing from yourADB.java
snippet