Android app中获取root权限和运行任意命令

直接放方法PS:kotlin中称为function(函数)吧,不管哈哈哈,java是世界上最好的语言,但是还是练习下kotlin。

fun suCmd(cmd: String): String {
        var process: Process? = null
        var os: DataOutputStream? = null
        var ls: DataInputStream? = null
        var result: String = ""
        try {
            process = Runtime.getRuntime().exec("su")
            os = DataOutputStream(process.outputStream)
            ls = DataInputStream(process.inputStream)
            os.writeBytes(cmd + "\n")
            os.writeBytes("exit\n")
            os.flush()
            var line = ls.readLine()
            while (line != null) {
                result += line
                line = ls.readLine()
            }
            process.waitFor()
        } catch (e: Exception) {
            Log.e("varenyzc", "Exception: " + e.toString())
        } finally {
            try {
                os?.close()
                ls?.close()
                process?.destroy()
            } catch (e: Exception) {
                Log.e("varenyzc", "close stream exception: " + e.toString())
            }
        }
        Log.d("varenyzc", "result: " + result)
        return result
    }

该方法调用后会返回执行命令的结果,结果以String回传。
通过调用这个方法,可以运行任意的命令,若要获取root权限,调用以下方法即可:

suCmd("chmod 777 $packageCodePath")

你可能感兴趣的:(Android app中获取root权限和运行任意命令)