如何通过Android应用程序向终端发送命令并获取输出?例如,发送“ls /”并获取输出以在GUI中打印它?
答案 0 :(得分:13)
你必须使用反射来调用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;
}
答案 1 :(得分:1)
可以在此处找到不同的解决方案:http://code.google.com/p/market-enabler/wiki/ShellCommands 我还没有测试过它们。
答案 2 :(得分:1)
尝试这个答案有办法以编程方式在android上运行shell命令 https://stackoverflow.com/a/3350332/2425851