1

I want to execute android shell command from my android app to execute a uiautomator test jar.

i have tried following options. but neither of them is working for me...

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

Also tried...

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();
}

Please tell what mistake i m doing?

2 Answers 2

1

Android 5.0 solved your problem. Here is new API using which you can execute shell commands.Check here : executeShellCommand (String command)

Enjoy!!!

Sign up to request clarification or add additional context in comments.

Comments

0

Try this, i added an output reading process also. But you'll need to cut up your shell command:

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.