android sudo and shell

来源:互联网 发布:js水仙花数 编辑:程序博客网 时间:2024/06/14 18:44

最近频繁用到su和shell的东西,在android上跑一些东西,贴下代码,做个笔记吧

SuperUserShell

public class SuperUserShell {    private Process su;    private DataOutputStream outputStream;    void open() throws IOException {        this.su = Runtime.getRuntime().exec("su");        this.outputStream = new DataOutputStream(su.getOutputStream());    }    void write(String cmd) throws IOException, InterruptedException {        outputStream.writeBytes(cmd + "\n");        outputStream.flush();    }    void close() {        if (su == null || outputStream == null) return;        try {            outputStream.writeBytes("exit\n");            outputStream.flush();            su.waitFor();            outputStream.close();            su.getInputStream().close();            su.getErrorStream().close();        } catch (Exception e) {            e.printStackTrace();        }    }}

Shell

public class Shell {    private Process shell;    private DataOutputStream outputStream;    private BufferedReader responseStream;    public void open() throws IOException, InterruptedException {        this.shell = Runtime.getRuntime().exec("sh");        this.outputStream = new DataOutputStream(shell.getOutputStream());        this.responseStream = new BufferedReader(new InputStreamReader(shell.getInputStream()));    }    public void write(String cmd) throws IOException, InterruptedException {        outputStream.writeBytes(cmd + "\n");        outputStream.flush();    }    public String read() throws IOException, InterruptedException {        String line;        while (true) {            if ((line = responseStream.readLine()) != null) break;        }        return line.trim();    }    public void close() {        if (shell == null || outputStream == null) return;        try {            outputStream.writeBytes("exit\n");            outputStream.flush();            shell.waitFor();            outputStream.close();            responseStream.close();            shell.getErrorStream().close();        } catch (Exception e) {            e.printStackTrace();        }    }}
原创粉丝点击