How to send a command to the terminal through android app and get the output back? For example, sending "ls /" and getting the output to print it in the GUI?
Asked
Active
Viewed 3.0k times
3 Answers
13
You have to use reflection to call android.os.Exec.createSubprocess():
public String ls () {
Class<?> execClass = Class.forName("android.os.Exec");
Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
int[] pid = new int[1];
FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
String output = "";
try {
String line;
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
}
catch (IOException e) {}
return output;
}

Josh Gao
- 2,525
- 23
- 21
-
Oops, that'd be the reflected class. – Josh Gao May 17 '10 at 10:50
-
4I'm getting "java.lang.ClassNotFoundException: android.os.Exec" – ademar111190 Sep 18 '13 at 20:40
1
Try this answer there is way to run shell commands on android programmatically https://stackoverflow.com/a/3350332/2425851

Community
- 1
- 1

NickUnuchek
- 11,794
- 12
- 98
- 138
1
Different solutions could be found here: http://code.google.com/p/market-enabler/wiki/ShellCommands I've not tested them yet.

Osama Gamal
- 1,161
- 4
- 12
- 18