Android在应用程序中运行bash命令
问题内容:
嗨,我正在开发一个需要我运行一些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;
}
感谢您对我的问题的任何帮助
问题答案:
如果我理解正确,那么您要做的就是将单行示例方法更改为可以接受并发送多行的方法,如下所示:
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"));