我正在尝试运行
String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);
在我的应用程序中,但似乎语法有点错误。不过,我从手机上的终端模拟器应用程序运行它没有问题,所以我只是不明白为什么从我的应用程序中调用它时它不起作用。
任何帮助都深表感谢!
找到解决方案!感谢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
使用以下功能:
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");