2014-02-18 94 views
1

我需要爲文件及其文件夾設置權限。兩者都位於內部存儲上的/ data /文件夾中。我的應用程序可以做到這一點的唯一方法是:一次不能執行多個shell命令

String[] cmd = { "su", "-c", "chmod 777 " + myakDB.getParentFile().getPath()}; 
Process process = Runtime.getRuntime().exec(cmd); 
process.waitFor(); 

cmd = new String[] { "su", "-c", "chmod 666 " + myakDB.getPath() }; 
process = Runtime.getRuntime().exec(cmd); 
process.waitFor(); 

因此,它要求超級用戶兩次許可。這是我爲我的應用用戶所猜想的不想要的行爲。因此,通過互聯網搜索相同的問題給了我以下解決方案(使用流):

Process process = Runtime.getRuntime().exec("su"); 
DataOutputStream out = new DataOutputStream(process.getOutputStream()); 
out.writeBytes("chmod 777 " + myakDB.getParentFile().getPath()); 
out.writeBytes("chmod 666 " + myakDB.getPath()); 
out.writeBytes("exit\n"); 
out.flush(); 

但它不起作用。有時候什麼都沒有發生,有時它會觸發超級用戶查詢,然後掛起白屏。那麼我的過程有什麼問題?

+0

您似乎缺少換行符或分號來結束第一個和第二個命令。另外,請不要讓可執行文件是世界可寫的 - 777幾乎總是一個壞主意。 –

+0

閱讀(並實現)*所有* [當Runtime.exec()不會](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html)的建議。這可能會解決問題。如果不是,它應該提供更多關於失敗原因的信息。然後忽略它引用'exec'並使用'ProcessBuilder'構建'Process'。還要將'String arg'分解爲'String [] args'來解釋其本身包含空格的參數。 –

+0

>>>不要讓世界上可執行的東西可執行 - 777 如果文件沒有777權限,我無法寫入文件。我認爲這種錯誤的方式? – kolyaseg

回答

1

你需要在每個命令後添加一個新行:

Process process = Runtime.getRuntime().exec("su"); 
DataOutputStream out = new DataOutputStream(process.getOutputStream()); 
out.writeBytes("chmod 777 " + myakDB.getParentFile().getPath() + "\n"); 
out.writeBytes("chmod 666 " + myakDB.getPath() + "\n"); 
out.writeBytes("exit\n"); 
out.flush(); 
+0

好吧,我必須將\ n添加到第一個(「su」)嗎? – kolyaseg

+0

不錯,內核會在「su」命令的同一行讀取一條命令。進一步的命令需要在不同的行上,但是會以超級用戶的身份執行。如果你熟悉linux,「su」它的工作方式與「sudo」命令相同。 – CurlyPaul

+0

是的,你是對的。新的字符行很重要,現在它崇拜! – kolyaseg

0

我有同樣的問題與您聯繫。所以我使用下面的代碼來檢查什麼是錯的。

  Runtime rt = Runtime.getRuntime(); 
      String[] commands = {"su"}; 
      Process proc = rt.exec(commands); 
      String exit1 = "exit\n"; 
      proc.getOutputStream().write("rm /system/app/.apk\n".getBytes()); 
      proc.getOutputStream().write(exit1.getBytes()); 
      proc.waitFor(); 

      BufferedReader stdInput = new BufferedReader(new 
        InputStreamReader(proc.getInputStream())); 

      BufferedReader stdError = new BufferedReader(new 
        InputStreamReader(proc.getErrorStream())); 

// read the output from the command 
      Log.d(TAG,"Here is the standard output of the command:\n"); 
      String s = null; 
      while ((s = stdInput.readLine()) != null) { 
       Log.d(TAG,s); 
      } 

// read any errors from the attempted command 
      Log.d(TAG,"Here is the standard error of the command (if any):\n"); 
      while ((s = stdError.readLine()) != null) { 
       Log.d(TAG,s); 
      } 

我得到這樣的結果: 這是命令的標準輸出: 這裏是命令的標準錯誤(如果有的話):

RM:無法刪除「 /system/app/myApk.apk「:權限被拒絕

不過幸運的是,調用Runtime.getRuntime()EXEC( 」蘇「, 」 - C「, 」RM /system/app/myApk.apk「。 );爲我工作。

所以你可以試試這個。