我在使用参数执行 su 时遇到问题(包含空格?!)。我的 Command.java 看起来像这样:
public class Command
{
Process process;
public String executeCommand(String command)
{
StringBuffer output = new StringBuffer();
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
String response = output.toString();
return response;
}
}
在我的 MainActivity 中,它适用于单个命令。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView content = (TextView) findViewById(R.id.txt_content);
Command cmd = new Command();
String outp = cmd.executeCommand("su -c 'id'");
Log.d("OOOOOOUT", outp);
content.setText(outp);
}
结果表明,它正在工作:
D/OOOOOOUT: uid=0(root) gid=0(root) context=u:r:init:s0
这也适用于 ls 命令。但是当我尝试用参数解析参数时,它不会被执行。
E.g.
String outp = cmd.executeCommand("su -c 'ls /data/data/'");
Log.d("OOOOOOUT", outp);
content.setText(outp);
我还尝试了以下方法:
String outp = cmd.executeCommand("su -c \'ls /data/data/\'");
String outp = cmd.executeCommand("su -c 'ls -l'");
甚至更多。当我直接在 shell 中执行此命令时,我得到以下输出:
shell@hammerhead:/ $ su -c 'ls -l'
drwxr-xr-x root root 1970-06-20 18:01 acct
drwxrwx--- system cache 2016-06-21 22:06 cache
-rwxr-x--- root root 272364 1970-01-01 01:00 charger
dr-x------ root root 1970-06-20 18:01 config
我还尝试使用完整路径:
shell@hammerhead:/ $ /system/xbin/su -c 'ls -l'
drwxr-xr-x root root 1970-06-20 18:01 acct
drwxrwx--- system cache 2016-06-21 22:06 cache
也在应用程序内。我猜这是一个解析错误。有时我看到有人在命令末尾添加“\n”?不知道为什么。我真的很感谢这个主题中的任何帮助。谢谢!