xcy396
11/18/2017 - 9:39 AM

Root

import java.io.DataOutputStream;
import java.io.OutputStream;

/**
 * Created by Mark Xu on 2017/11/2.
 * Site: http://xuchongyang.com
 */

public class RootUtil {
    /**
     * 为当前应用请求 Root 权限
     * @param pkgCodePath pkgCodePath
     * @return 请求结果
     */
    public static boolean upgradeRootPermission(String pkgCodePath) {
        Process process = null;
        DataOutputStream os = null;
        try {
            String cmd="chmod 777 " + pkgCodePath;
            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }

    /**
     * 执行 Shell 命令
     * @param cmd 命令
     */
    private void execShellCmd(String cmd) {
        try {
            // 申请获取root权限,这一步很重要,不然会没有作用
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}