Android examples for Android OS:Shell
do Shell Command
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; import android.util.Log; public class Main{ public static int doShellCommand(String[] cmds, ShellCallback sc, boolean runAsRoot, boolean waitFor) throws Exception { Process proc = null;/* ww w . j a v a2s .c om*/ int exitCode = -1; if (runAsRoot) proc = Runtime.getRuntime().exec("su"); else proc = Runtime.getRuntime().exec("sh"); final char buf[] = new char[20]; // Consume the "stdout" InputStreamReader reader = new InputStreamReader( proc.getInputStream()); int read = 0; while ((read = reader.read(buf)) != -1) { sc.shellOut(buf); } // Consume the "stderr" reader = new InputStreamReader(proc.getErrorStream()); read = 0; while ((read = reader.read(buf)) != -1) { sc.shellOut(buf); } OutputStreamWriter out = new OutputStreamWriter( proc.getOutputStream()); for (int i = 0; i < cmds.length; i++) { logMessage("executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor); out.write(cmds[i]); out.write("\n"); } out.flush(); out.write("exit\n"); out.flush(); // if (waitFor) // { exitCode = proc.waitFor(); // } return exitCode; } public static void logMessage(String msg) { } }