【问题标题】:Show Processes of Shell Script显示Shell脚本进程
【发布时间】:2011-05-16 03:01:36
【问题描述】:

我有以下方法在我的 java 应用程序中运行 shell 命令,我正在寻找运行一些脚本,例如修复用户手机上所有应用程序权限的脚本。我可以使用这个命令运行脚本没问题 execCommand("/system/xbin/fix_perm");但是问题是我只想打印出正在执行的操作,例如终端仿真器如何获取输出流并将其打印在屏幕上?感谢您的帮助

public Boolean execCommand(String command) 
{
    try {
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream()); 
        os.writeBytes(command + "\n");
        os.flush();
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (IOException e) {
        return false;
    } catch (InterruptedException e) {
        return false;
    }
    return true;
}

【问题讨论】:

    标签: java android text printing


    【解决方案1】:

    我希望您意识到允许用户以 su 的身份运行任意命令的潜在极端后果,并且会指出一个可能的解决方案。

    public Boolean execCommand(String command) 
    {
        try {
            Runtime rt = Runtime.getRuntime();
            Process process = rt.exec("su");
    
            // capture stdout
            BufferedReader stdout = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            // capture stderr
            BufferedReader stderr = new BufferedReader(
                new InputStreamReader(process.getErrorStream()));
    
            DataOutputStream os = new DataOutputStream(process.getOutputStream()); 
            os.writeBytes(command + "\n");
            os.flush();
    
            String line = null;
            StringBuilder cmdOut = new StringBuilder();
            while ((line = stdout.readLine()) != null) {
                cmdOut.append(line);
            }
            stdout.close();
            while ((line = stderr.readLine()) != null) {
                cmdOut.append("[ERROR] ").append(line);
            }
            stderr.close();
    
            // Show simple dialog
            Toast.makeText(getApplicationContext(), cmdOut.toString(), Toast.LENGTH_LONG).show();
    
            os.writeBytes("exit\n");
            os.flush();
    
            // consider dropping this, see http://kylecartmell.com/?p=9
            process.waitFor(); 
        } catch (IOException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        }
        return true;
    }
    

    【讨论】:

    • System.out.println() 对 Android 设备有什么帮助吗?
    • 不是真的(虽然可以在你的 IDE 中显示),已将其更改为使用 Android 记录器。
    • 是的......但我认为 OP 想在设备的屏幕上显示它。
    • 是的,我想在设备屏幕上而不是在日志中显示它模拟器我只想显示我想在我的应用程序中运行的几个脚本的进程
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多