命令我想在我的應用程序運行語法殼在Android應用
String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);
,但它似乎是語法錯誤莫名其妙。但是,我從手機上的終端模擬器應用程序運行它並沒有問題,所以我不明白爲什麼在我的應用程序中調用它時無法正常工作。
任何幫助深表感謝!
命令我想在我的應用程序運行語法殼在Android應用
String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);
,但它似乎是語法錯誤莫名其妙。但是,我從手機上的終端模擬器應用程序運行它並沒有問題,所以我不明白爲什麼在我的應用程序中調用它時無法正常工作。
任何幫助深表感謝!
解決方案找到了!感謝onithere建議的鏈接。請參閱下面的代碼:要使超級用戶shell命令正常工作,首先需要創建一個超級用戶shell並將其分配給進程,然後分別對其輸入和輸出流進行寫入和讀取。
Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
//from here all commands are executed with su permissions
stdin.writeBytes("ls /data\n"); // \n executes the command
InputStream stdout = p.getInputStream();
byte[] buffer = new byte[BUFF_LEN];
int read;
String out = new String();
//read method will wait forever if there is nothing in the stream
//so we need to read it in another way than while((read=stdout.read(buffer))>0)
while(true){
read = stdout.read(buffer);
out += new String(buffer, 0, read);
if(read<BUFF_LEN){
//we have read everything
break;
}
}
//do something with the output
它不起作用! ,什麼是BUFF_LEN,請仔細複印。投票 – famfamfam 2016-02-28 09:16:59
@famfamfam BUFF_LEN是一個全局變量,它存儲輸入緩衝區的長度,沒有理由downvote,因爲你不知道的東西。此代碼也是在幾年前編寫的,現在的Android API可能現在做的事情非常不同。 – restInPieces 2016-03-01 16:19:29
使用下面的功能:
public void shellCommandRunAsRoot(String Command)
{
try
{
Process RunProcess= Runtime.getRuntime().exec("su");
DataOutputStream os;
os = new DataOutputStream(RunProcess.getOutputStream());
os.writeBytes(cmds+"\n");
os.writeBytes("exit+\n");
os.flush();
}
catch (IOException e)
{
// Handle Exception
}
}
用法:
shellCommandRunAsRoot("pkill firefox");
請問您的應用程序具有超級用戶權限?應用程序權限與終端權限不同。 – onit 2012-02-21 19:08:17
我的知識是有限的,但我明白,一個應用程序不能擁有超級用戶權限,只有產生的進程。順便說一句,超級用戶的應用程序通知我,如果我運行說「su -c id」,並且輸出是正確的,那麼已經授予了root權限。你有什麼建議?非常感謝 – restInPieces 2012-02-22 09:09:46
不完全確定什麼是錯的。然而,似乎有很多其他話題在stackoverflow可能會幫助你,如果你搜索。 http://stackoverflow.com/questions/7216071/how-to-run-multiple-shell-commands-through-an-app-in-android。 http://stackoverflow.com/questions/6896618/read-command-output-inside-su-process – onit 2012-02-22 14:54:58