首页 > 代码库 > Android平台 Runtime.getRuntime().exec
Android平台 Runtime.getRuntime().exec
import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;public class RootCmd { private static boolean mHaveRoot = false; public static boolean haveRoot() { if (!mHaveRoot) { int ret = execRootCmdSilent("echo test"); if (ret != 1) { System.out.println("have root!"); mHaveRoot = true; } else { System.out.println("not root!"); } } else { System.out.println("mHaveRoot = true, have root!"); } return mHaveRoot; } @SuppressWarnings("deprecation") public static String execRootCmd(String cmd) { String result = ""; DataOutputStream dos = null; DataInputStream dis = null; try { Process p = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(p.getOutputStream()); dis = new DataInputStream(p.getInputStream()); System.out.println(cmd); dos.writeBytes(cmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); String line = null; while ((line = dis.readLine()) != null) { result += line; } p.waitFor(); } catch (Exception e) { e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static int execRootCmdSilent(String cmd) { int result = -1; DataOutputStream dos = null; try { Process p = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(p.getOutputStream()); System.out.println(cmd); dos.writeBytes(cmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); p.waitFor(); result = p.exitValue(); } catch (Exception e) { e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。