通过 android app 获取执行命令的输出

Get the output from executed commands through android app

我正在执行以下代码以在我正在创建的 android 应用程序中执行 linux 命令:

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();
}

我想知道是否有办法知道命令执行后返回的是什么。例如,如果我这样做 "ls" 我想看看命令通常会输出什么。

试试这个代码:

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) {}

我们来看一个“字符串函数”示例

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;
     }

现在就用它:

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