shell Execute - Android Android OS

Android examples for Android OS:Shell

Description

shell Execute

Demo Code

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

import android.util.Log;

public class Main {

  public static final String TAG = "SystemUtil";

  public static BufferedReader shellExecute(String command, boolean requireRoot) {
    return shellExecute(new String[] { command }, requireRoot);
  }//  w ww.ja va2 s.c  o  m

  public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;
    DataOutputStream out = null;
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
      shell = Runtime.getRuntime().exec(startCommand);
      out = new DataOutputStream(shell.getOutputStream());
      reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
      for (String command : commands) {
        out.writeBytes(command + "\n");
        out.flush();
      }
      out.writeBytes("exit\n");
      out.flush();
      shell.waitFor();
    } catch (Exception e) {
      Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (Exception e) {

      }
    }
    return reader;
  }

}

Related Tutorials