Taranfx
Taranfx

Reputation: 10437

Running shell commands from app [Rooted]

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?

Upvotes: 5

Views: 6470

Answers (2)

sarwar
sarwar

Reputation: 2845

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.

Upvotes: 5

PravinCG
PravinCG

Reputation: 7708

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

Upvotes: 2

Related Questions