如何在安卓应用中运行终端命令?
如何通过安卓应用向终端发送命令并取回输出?例如,发送“ls /”并获取输出以在GUI中打印它?
如何通过安卓应用向终端发送命令并取回输出?例如,发送“ls /”并获取输出以在GUI中打印它?
你必须使用反射来调用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;
}