如何在Android应用程序中运行终端命令?

16

如何通过安卓应用发送命令到终端并获取输出?例如,发送“ls /”并将输出打印在GUI中。

3个回答

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;
}

哎呀,那应该是反射类。 - Josh Gao
4
我遇到了“java.lang.ClassNotFoundException: android.os.Exec”这个错误。 - ademar111190

1

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接