tags:

views:

53

answers:

1

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?

A: 

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());
    }
}
Aaron C
thank you so much... what would be required to modify this to run multiple shell commands?
Frank Bozzo
Worst case you can call this function for each command, but you should be able to separate each command with a newline character \n
Aaron C