shell Execute and return result - Android Android OS

Android examples for Android OS:Shell

Description

shell Execute and return result

Demo Code


//package com.java2s;
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);
    }/*from  www .j  a  v  a2 s .co  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