显示Shell脚本的进程

时间:2011-05-16 03:01:36

标签: java android text printing

我有以下方法在我的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;
}

1 个答案:

答案 0 :(得分:0)

我希望您了解允许用户以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;
}