在android应用中执行su命令

执行普通的su命令,条件是设备root,且允许应用执行su命令

// 公共函数:执行命令并获取输出
    private fun executeProcess(command: Array<String>): String {
        var process: Process? = null
        val output = StringBuilder()

        try {
            process = Runtime.getRuntime().exec(command)
            output.append(readProcessOutput(process))
        } catch (e: Exception) {
            output.append("Exception: ").append(e.message)
        } finally {
            process?.destroy()
        }

        return logAndReturn("execSuCommand", command.joinToString(" "), output.toString())
    }

比如可以通过 executeProces(listof(“su”,"0","id"))来测试是否有su执行权限

相当于执行

2. 另外一种执行,是交互式命令,在命令执行的输出流中再写命令,并执行等待结果

private fun execSu548Command(command: String): String {
        val output = StringBuilder()
        var process: Process? = null
        try {
            // 获取 su 权限
            process = Runtime.getRuntime().exec("su 548")
            val os = process.outputStream
            val dos = DataOutputStream(os)
            // 写入要执行的命令
            dos.writeBytes(command + "\n")
            dos.writeBytes("exit\n")
            dos.flush()
            // 读取标准输出
            val reader = BufferedReader(
                InputStreamReader(process.inputStream)
            )
            var line: String?
            while ((reader.readLine().also { line = it }) != null) {
                output.append(line).append("\n")
            }
            // 读取错误输出
            val errorReader = BufferedReader(
                InputStreamReader(process.errorStream)
            )
            while ((errorReader.readLine().also { line = it }) != null) {
                output.append(line).append("\n")
            }
            // 等待执行结束
            process.waitFor()
        } catch (e: java.lang.Exception) {
            output.append("Exception: ").append(e.message)
        } finally {
            if (process != null) {
                process.destroy()
            }
        }
        val result = output.toString().trim { it <= ' ' }
        LogUtils.d("$TAG execSuCommand $command,result $result")
        return result
    }

相当于

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值