如何从Android应用程序执行shell命令?

时间:2014-06-15 20:34:49

标签: java android

我想从我的Android应用程序执行android shell命令来执行uiautomator测试jar。

我尝试了以下选项。但他们都没有为我工作......

 public void execute(String shellcommand) {
        Runtime rt = Runtime.getRuntime();
        Process p = r.exec(new String[]{"/system/bin/sh", "-c", shellcommand});
 }

还试过......

public void execute(String shellcommand) {
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes(shellcommand + "\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}

请说出我在做什么错误?

2 个答案:

答案 0 :(得分:0)

试试这个,我也添加了一个输出读取过程。但是你需要切断你的shell命令:

ProcessBuilder pb = new ProcessBuilder("adb", "shell", "uiautomator", "runtest", "/data/local/tmp/MyJar.jar", "-c", "com.my.test.Class#testmethod", "-e someparameter someparameterName");
Process pc;
try {
    pc = pb.start();
    InputStream stdin = pc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    InputStreamReader esr = new InputStreamReader(pc.getErrorStream());
    BufferedReader errorReader = new BufferedReader(esr);
    pc.waitFor();
} catch (IOException e) {
    e.printStackTrace();
    Assert.fail(e.getMessage());

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    Assert.fail(e.getMessage());
}

答案 1 :(得分:0)

Android 5.0解决了您的问题。以下是可以执行shell命令的新API。请在此处查看:executeShellCommand (String command)

享受!!!