android 调用shell命令

网上找了好多都不能用,最后群里一朋友给了段代码可以用,记录下

public String exec(String xx) {
    Runtime ex = Runtime.getRuntime();
    String cmdBecomeSu = "/system/bin/sh -";
    String script = xx;
    try
    {
        java.lang.Process runsum = ex.exec(cmdBecomeSu);
        int exitVal = 0;
        final OutputStreamWriter out = new OutputStreamWriter(runsum.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(runsum.getInputStream()));
        out.write(script);
        out.write("\n");
        out.flush();
        out.write("exit\n");
        out.flush();
        out.close();
        String s = "";
        String line = null;
        while ((line = in.readLine()) != null) {
            s += line + "\n";
        }
        in.close();
        exitVal = runsum.waitFor();
        if (exitVal == 0)
        {
            Log.e("Debug", "Successfully to shell");
            return s;
        }
    }
    catch ( Exception e)
    {
        Log.e("Debug", "Fails to shell");
    }
    return cmdBecomeSu;
}

标签: none

评论已关闭