【问题标题】:Get the output from executed commands through android app通过android app获取执行命令的输出
【发布时间】:2015-09-05 16:34:53
【问题描述】:

我正在执行以下代码以在我正在创建的 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”,我想看看该命令通常会输出什么。

【问题讨论】:

    标签: java android linux command-line root


    【解决方案1】:

    试试这个代码:

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

    【讨论】:

    • 但是如果我使用 writeBytes() 来执行命令,这仍然有效吗?
    • 我会试试,我会给你答案
    【解决方案2】:

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

    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");
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多