5

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?

2 Answers 2

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.

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

2 Comments

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?
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 :)
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");

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.