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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2843250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:31:16  来源:igfitidea点击:

How to run terminal command in Android application?

javaandroidterminal

提问by Osama Gamal

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?

如何通过android应用程序向终端发送命令并取回输出?例如,发送“ls /”并获取输出以在GUI中打印它?

采纳答案by Josh Gao

You have to use reflection to call android.os.Exec.createSubprocess():

您必须使用反射来调用 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;
}

回答by Osama Gamal

Different solutions could be found here: http://code.google.com/p/market-enabler/wiki/ShellCommandsI've not tested them yet.

可以在这里找到不同的解决方案:http: //code.google.com/p/market-enabler/wiki/ShellCommands我还没有测试过它们。

回答by NickUnuchek

Try this answer there is way to run shell commands on android programmatically https://stackoverflow.com/a/3350332/2425851

试试这个答案有办法在android上以编程方式运行shell命令 https://stackoverflow.com/a/3350332/2425851