2011-08-27 148 views
2

我试图通过我的应用程序运行3个不同的命令,但只有第一个执行。 这是代码。如何通过android中的应用程序运行多个shell命令

Process process = Runtime.getRuntime().exec("su"); 
process = Runtime.getRuntime().exec("mount -o remount,rw /system"); 
process = Runtime.getRuntime().exec("cp /sdcard/hosts /system/etc"); 

我得到root访问权限,但之后没有其他事情发生。

编辑:我想这个代码,但这样也只能执行苏COMAND

String[] commands = {"mount -o remount,rw /system", "cp /sdcard/hosts /system/etc"}; 

         Process p = Runtime.getRuntime().exec("su"); 
         DataOutputStream os = new DataOutputStream(p.getOutputStream());    
         for (String tmpCmd : commands) { 
           os.writeBytes(tmpCmd+"\n"); 
         }   
         os.writeBytes("exit\n"); 
         os.flush(); 

编辑:这在时间工作,但只需要一个命令,我不得不做出一个按钮,每一个命令。

String[] hin1 = { "su", "-c","cp /sdcard/Mediafire/hosts /system/etc/" }; 
        try { 
         Runtime.getRuntime().exec(hin1); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
+0

可能重复(http://stackoverflow.com/questions/6882248/running-shell-commands-though [运行壳牌虽然在Android Java代码指令] -java-code-on-android) –

回答

3

这很容易做到。

使用“根工具”。

从以下链接添加jar文件: https://github.com/Stericson/RootTools

Command command = new Command(0, "echo this is a command", "echo this is another command"){ 
     @Override 
     public void output(int id, String line) 
     { 
      //Do something with the output here 
     } 
}; 
RootTools.getShell(true).add(command).waitForFinish(); 
1

Exec的运行在一个单独的进程的命令,所以我希望“苏”的影响,一旦过程完成丢失。所以也许装载失败,因为它在一个单独的过程中,其中su没有被应用。

你可以把你的命令序列放在单个文件中执行吗?

或者你可以使用su -c来完成一项命令中的工作?

+0

你能告诉我如何在这里使用su -c吗? – Arveen

+0

你可以使用shell &&将mount和cp合并为一个命令吗? – djna

2

因为su hack既不能用于(也不能在类Unix系统上运行),所以root不是“粘性的”,可以更改现有进程的用户标识。

su的某些版本将允许您指定要执行的命令及其参数。但其他人不会,而是要求您打开由su程序创建的超级用户shell的输入流,并将命令压入,就好像您正在键入它们一样。

我没有提供示例,而是建议将该问题作为提供代码的副本关闭。

+0

请参阅我的编辑 – Arveen

+0

您有植根设备吗?如果不是,那么这段时间不起作用。如果是这样,那么在引用的问题中已经解决的问题是没有意义的。 –

+0

我有一个扎根设备和su工程,但其他命令甚至不显示在logcat中。 – Arveen

1

容易的&

Process process = Runtime.getRuntime().exec("su & mount -o remount,rw /system"); 
相关问题