2011-08-27 90 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"); 
相關問題