Android Root使用参数执行su

时间:2016-07-11 15:51:22

标签: android parameters command root su

我遇到问题,用参数执行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”?不知道为什么。我非常感谢这个主题中的任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为将参数传递给su命令的方法是使用字符串数组:

Runtime.getRuntime().exec(new String[]{"su","-c", "ls /data/data/"});
相关问题