Android获取Root权限和执行Shell脚本

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ShellUtil {

    /**
     * 获取Root权限
     *
     * @return
     */
    public static boolean getRoot() {
        boolean res = false;
        try {
            Process process = Runtime.getRuntime().exec("su -c exit");
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                res = true;
            }
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 执行Shell命令(必须有Root权限)
     *
     * @param cmd
     */
    public static String execShell(String cmd) {
        StringBuffer sb = new StringBuffer();
        try {
            Process process = Runtime.getRuntime().exec("su -c " + cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            reader.close();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 获取FD数量
     *
     * @return
     */
    public static int getFDNumber() {
        int res = 0;
        try {
            int pid = android.os.Process.myPid();
            Process process = Runtime.getRuntime().exec("ls /proc/" + pid + "/fd");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while (reader.readLine() != null) {
                res++;
            }
            reader.close();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}

发表评论