Execute shell commands and get output in a TextView Execute shell commands and get output in a TextView shell shell

Execute shell commands and get output in a TextView


You can run command and display command output into text as below :

public class MainActivity extends Activity {    TextView tv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv=(TextView)findViewById(R.id.cmdOp);        tv.setText("Output :"+"\n"+runAsRoot());    }    public String runAsRoot() {        try {            // Executes the command.            Process process = Runtime.getRuntime().exec("ls -l");            // Reads stdout.            // NOTE: You can write to stdin of the command using            //       process.getOutputStream().            BufferedReader reader = new BufferedReader(                    new InputStreamReader(process.getInputStream()));            int read;            char[] buffer = new char[4096];            StringBuffer output = new StringBuffer();            while ((read = reader.read(buffer)) > 0) {                output.append(buffer, 0, read);            }            reader.close();            // Waits for the command to finish.            process.waitFor();            return output.toString();        } catch (IOException e) {            throw new RuntimeException(e);        } catch (InterruptedException e) {            throw new RuntimeException(e);        }    }}

Note : The "su" command does only run if the device is rooted. Otherwise it throws an exception.


I think the problem is that you wait for 5s to start reading the output and when the program starts it reaches the end of the stream because it is faster than the speed the log is generated. Thus you need to wait again for some time and start reading the buffer again. The following code works for me. I use ArrayAdapter + ListView instead of TextView. If we set m_bTerminate to true then the thread dies next time it reaches the end of the input stream.

Process p = Runtime.getRuntime().exec(m_command);InputStream is = p.getInputStream();while(!m_bTerminate) {    while(is.available() <= 0)    {        try{ Thread.sleep(1000, 0); } catch(Exception e) {m_log.e(e);}    }    byte[] buff = new byte[4096];    int read = is.read(buff);    if(0 < read) {        m_List.add(new String(buff, 0, read));        m_handler.sendEmptyMessage(Handler.MSG_RADIO_LOG_NOTIFY_DATASET_CHANGED);        //if we call notify datasetchanged directly it raises        //android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views        //m_Adapter.notifyDataSetChanged();    }}m_log.p(TAG, Log.DEBUG, "Command executed. Destroying thread.");is.close();p.destroy();


Take this String function and store the result into your TextView or wherever you want

public String shell_exec(String cmd)     {     String o=null;     try       {       Process p=Runtime.getRuntime().exec(cmd);       BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));       String line;       while((line=b.readLine())!=null)o+=line;       }catch(Exception e){o="error";}     return o;     }

Example of usage:

mytextview.setText(shell_exec("ls -l"));