Android examples for Android OS:Shell
Send a command to the shell.
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import android.util.Log; public class Main{ private static final String LOG_TAG = ShellHelper.class.getSimpleName(); /**/* ww w . j av a 2s. c om*/ * Send a command to the shell. * @param command The command execute. * @return A list of strings containing each line of the output. * @see java.lang.Runtime.getRuntime().exec() * @see java.io.BufferedReader.readLine() * @throws IOException if the requested command cannot be executed * or if some other IOException occurs. */ public static List<String> exec(String command) throws IOException, SecurityException { return exec(command, true); } /** * @param trimOutput * trim whitespace from the beginning and end of * each line of the command output. Defaults to true. */ public static List<String> exec(String command, boolean trimOutput) throws IOException, SecurityException { List<String> list = new ArrayList<String>(); BufferedReader stdInput = null; try { Process p = Runtime.getRuntime().exec(command); stdInput = new BufferedReader(new InputStreamReader( p.getInputStream())); String s; while ((s = stdInput.readLine()) != null) { if (trimOutput) { s = s.trim(); if (s.length() != 0) list.add(s); } else list.add(s); } } catch (IOException e) { Log.e(LOG_TAG, "IOException occurred while executing '" + command + "'."); throw e; } catch (SecurityException e) { Log.e(LOG_TAG, "SecurityException occurred while executing '" + command + "'."); throw e; } finally { stdInput.close(); } return list; } }