4

In my app, I want to run few shell command sand interpret the output. These commands are essentially the on that would run on rooted phone.

How do I do it?

Taranfx
  • 10,361
  • 17
  • 77
  • 95

2 Answers2

5

First make sure that the shell command that you need is actually available in Android. I've run into issues by assuming you can do things like redirect output with >.

This method also works on non-rooted phones of I believe v2.2, but you should check the API reference to be sure.

try {
        Process chmod = Runtime.getRuntime().exec("/system/bin/chmod 777 " +fileName);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(nfiq.getInputStream()));
        int read;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();
        while ((read = reader.read(buffer)) > 0) {
            output.append(buffer, 0, read);
        }
        reader.close();
        chmod.waitFor();
        outputString =  output.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

While it's probably not 100% necessary, it's a good idea to have the process wait for the exec to complete with process.waitFor() since you said that you care about the output.

sarwar
  • 2,835
  • 1
  • 26
  • 30
  • Some commands work like this (top, etc.), but other return an empty string even though there it output to the terminal when I run the commands from adb shell. E.g. process = Runtime.getRuntime().exec("/system/bin/ping"); Any idea why there would be nothing on the input stream? – David Doria Sep 17 '13 at 17:34
  • 1
    Ah, two separate problems. I was using readLine() to get the output of 'top', but the first thing in the output of 'top' is a newline character, so that explains the empty string. The other thing was that 'ping' was producing errors, and they were in getErrorStream() instead of getInputStream(). All is well now :) – David Doria Sep 17 '13 at 19:55
2

You need to first ensure you have busybox installed as that would install the list of most commonly used shell commands and then use the following code to run the command.

Runtime.getRuntime().exec("ls");
PravinCG
  • 7,688
  • 3
  • 30
  • 55