Android Root Script Method

Here is the method I use for executing root scripts in my Android app.


public static String execScript(String script)
{
  String output = "";
  String line;

  Process process;
  try
  {
    process = Runtime.getRuntime().exec("su");

    DataOutputStream stdin = new
    DataOutputStream(process.getOutputStream());
    DataInputStream stdout = new
    DataInputStream(process.getInputStream());
    DataInputStream stderr = new
    DataInputStream(process.getErrorStream());

    stdin.writeBytes(script + " \n");
    stdin.writeBytes("exit\n");

    stdin.flush();

    StringBuilder sb = new StringBuilder();

    while ((line = stdout.readLine()) != null)
    {
      sb.append(line);
      sb.append("\n");
    }

    while ((line = stderr.readLine()) != null)
    {
      sb.append(line);
      sb.append("\n");
    }

    output = sb.toString();

    process.waitFor();
    stderr.close();
    stdout.close();
    stdin.close();
  }
  catch (IOException e)
  {
  }
  catch (InterruptedException e)
  {
  }

  return output;
}

Share

Tagged as: , , , , , ,

Leave a Reply