Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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?

like image 563
Frank Bozzo Avatar asked Sep 27 '10 20:09

Frank Bozzo


People also ask

Can you run shell scripts in Android?

Steps: Connect Android phone to computer with USB cable. Open new Terminal window on your computer. Run “adb shell” command on the Terminal.

Can I run bash on Android?

So you want to get started making a bash script on your android phone. 1) GET QPYTHON. You need a text editor to use for coding.


1 Answers

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());
    }
}
like image 102
Aaron C Avatar answered Oct 17 '22 07:10

Aaron C