Get the output from executed commands through android app

3.3k Views Asked by At

I'm performing the following code to execute linux commands in my android application that I'm creating:

public void RunAsRoot(String[] cmds){
            Process p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());            
            for (String tmpCmd : cmds) {
                    os.writeBytes(tmpCmd+"\n");
            }           
            os.writeBytes("exit\n");  
            os.flush();
}

I want to know if there is a way to know what the command is returning after it is executing. for example, if I do "ls" I would like to see what the command wold normally output.

2

There are 2 best solutions below

2
On BEST ANSWER

try this code :

try {
  Process process = Runtime.getRuntime().exec("ls");
  BufferedReader bufferedReader = new BufferedReader(
  new InputStreamReader(process.getInputStream()));

  StringBuilder result=new StringBuilder();
  String line = "";
  while ((line = bufferedReader.readLine()) != null) {
    result.append(line);
  }
  TextView tv = (TextView)findViewById(R.id.textView1);
  tv.setText(result.toString());
  } 
catch (IOException e) {}
0
On

Let's go by a "String function" example

String shell_exec(String  s)
     {
     String line="",output="";
     try
       {
       Process p=Runtime.getRuntime().exec(new String[]{"sh","-c",s});
       BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
       while((line=b.readLine())!=null){output+=line+"\r\n";}
       }catch(Exception e){return "error";}
     return output;
     }

Now just use it:

String s=shell_exec("ls /data/data/com.mycompany.myapp");