【问题标题】:Android run bash command in appAndroid 在应用程序中运行 bash 命令
【发布时间】:2011-09-25 04:41:35
【问题描述】:

您好,我正在开发一个需要我运行一些 bash 代码的应用程序,有没有一种方法可以将脚本硬编码到我的应用程序中然后运行它?例如(这是一个非常简单的例子)

#!/system/bin/sh
#

if [ ! -f /sdcard/hello.txt ]
then
echo 'Hello World' >> /sdcard/hello.txt
else
echo 'Goodbye World' >> /sdcard/goodbye.txt
fi

我有以下方法来运行一行 bash 命令,但需要在多行上运行类似的东西。同样,上面的代码是一个非常简化的示例,我实际上正在做的事情必须通过脚本运行,而不能通过 java 来完成。我也想对其进行硬编码,我知道可以将脚本存储在手机上并使用以下命令运行它,但不希望脚本直接存在,而是将其硬编码在应用程序中。

public Boolean execCommand(String command) 
    {
        try {
            Runtime rt = Runtime.getRuntime();
            Process process = rt.exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream()); 
            os.writeBytes(command + "\n");
            os.flush();
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (IOException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        }
        return true; 
    }

感谢您对我的问题的任何帮助

【问题讨论】:

    标签: java android bash


    【解决方案1】:

    如果我理解正确,您所要做的就是将单行示例方法更改为接受和发送多行的方法,如下所示:

        public Boolean execCommands(String... command) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process process = rt.exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
    
            for(int i = 0; i < command.length; i++) {
                os.writeBytes(command[i] + "\n");
                os.flush();
            }
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (IOException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        }
        return true; 
    }
    

    这样,您可以像这样调用多行 bash 命令:

        String[] commands = {
                "echo 'test' >> /sdcard/test1.txt",
                "echo 'test2' >>/sdcard/test1.txt"
        };
    
        execCommands(commands);
    
        String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> /sdcard/foo.txt";
    
        execCommands(commandText.split("\n"));
    

    【讨论】:

    • 感谢代码将在几分钟内尝试一下,希望它运行良好:)
    • 完全按照我想要的方式工作,第二种运行方法将非常有帮助,非常感谢!
    • 我使用的是同样的东西,但它不适合我。它真的对你有用吗?我正在使用系统应用程序。
    猜你喜欢
    • 2023-04-04
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2020-05-14
    相关资源
    最近更新 更多