我正在尝试运行
String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);
在我的应用中,但似乎语法有点错误。我在手机上的终端模拟器应用程序中运行它没有问题,所以我无法理解为什么它在我的应用程序中调用时无效。
非常感谢任何帮助!
答案 0 :(得分:3)
解决方案!感谢onit here建议的链接。请参阅下面的代码:要使超级用户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
答案 1 :(得分:0)
使用以下功能:
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");