使用onClick执行多个shell命令

时间:2013-01-24 09:42:59

标签: java android shell command runtime.exec

这是我想要做的一个例子:

final String[] hwdebug1 = {"su","-c","echo hello > /system/hello1.txt"};

                 try {
                     Runtime.getRuntime().exec(hwdebug1);              
                } catch (IOException e) {
                }            

所以,如果我点击我的按钮,它可以很好地工作,但是如果,例如,我做的事情不是这样的:

final String[] hwdebug1 = {"su","-c","echo hello > /system/hello1.txt","echo hello > /system/hello2.txt","echo hello > /system/hello3.txt"};

我的意图是让按钮执行多于1个命令。我已经通过让它执行一个bash脚本来实现它,但我更愿意找到一种方法将它放在代码上。

谢谢!

使用Ben75方法解决

final String[] hwdebug1 = {"su","-c","echo hello > /system/hello1.txt"};
final String[] hwdebug2 = {"su","-c","echo hello > /system/hello2.txt"};
final String[] hwdebug3 = {"su","-c","echo hello > /system/hello3.txt"};
ArrayList<String[]> cmds = new ArrayList<String[]>();
cmds.add(hwdebug1);
cmds.add(hwdebug2);
cmds.add(hwdebug3);
for(String[] cmd:cmds){
    try {
       Runtime.getRuntime().exec(cmd);              
   } catch (IOException e) {
       e.printStacktrace(); 
   }          
}

1 个答案:

答案 0 :(得分:2)

Runtime.exec命令适用于单个命令,是cmd行字符串的简单“包装器”。

只需创建一个List并对其进行迭代:

final String[] hwdebug1 = {"su","-c","echo hello > /system/hello1.txt"};
final String[] hwdebug2 = {"su","-c","echo hello > /system/hello2.txt"};
final String[] hwdebug3 = {"su","-c","echo hello > /system/hello3.txt"};
ArrayList<String[]> cmds = new ArrayList<String[]>();
cmds.add(hwdebug1);
cmds.add(hwdebug2);
cmds.add(hwdebug3);
for(String[] cmd:cmds){
    try {
       Runtime.getRuntime().exec(cmd);              
   } catch (IOException e) {
       e.printStacktrace(); 
   }          
}