Frank Bozzo
Frank Bozzo

Reputation: 313

How do you run a shell script inside of an Android app?

I am trying to write an android app for root users that runs a series of shell commands, or a shell script if that is preferable, and displays the output... can anyone point me in the right direction?

Upvotes: 5

Views: 5315

Answers (1)

Aaron C
Aaron C

Reputation: 3313

This snippet requires root access, but will execute the given String as a shell command

void execCommandLine(String command)
{
    Runtime runtime = Runtime.getRuntime();
    Process proc = null;
    OutputStreamWriter osw = null;

    try
    {
        proc = runtime.exec("su");
        osw = new OutputStreamWriter(proc.getOutputStream());
        osw.write(command);
        osw.flush();
        osw.close();
    }
    catch (IOException ex)
    {
        Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
        return;
    }
    finally
    {
        if (osw != null)
        {
            try
            {
                osw.close();
            }
            catch (IOException e){}
        }
    }

    try 
    {
        proc.waitFor();
    }
    catch (InterruptedException e){}

    if (proc.exitValue() != 0)
    {
        Log.e("execCommandLine()", "Command returned error: " + command + "\n  Exit code: " + proc.exitValue());
    }
}

Upvotes: 8

Related Questions