android app代码中执行adb指令

方案1:使用Runtime类

    /**
     * 执行命令并且输出结果
     */
    public static String execRootCmd(String cmd) {
        String content = "";
        try {
            cmd = cmd.replace("adb shell","");
            Process process = Runtime.getRuntime().exec(cmd);
            Log.d(TAG,"process " + process.toString());
            content = process.toString();
        } catch (IOException e) {
            Log.d(TAG,"exception " + e.toString());
            e.printStackTrace();
        }
        return content;
    }

方案二、

class Cmd {
    private val TAG = "Cmd"
    
    val result = StringBuilder()
    
    fun run(cmd: String): Boolean {
        var bufferedReader: BufferedReader? = null
        var dos: DataOutputStream? = null
        var receive = ""
    
        try {
            Runtime.getRuntime().exec("su")?.run { // 经过Root处理的android系统即有su命令
                Logger.d("Cmd run: $cmd")
                bufferedReader = BufferedReader(InputStreamReader(inputStream))
                dos = DataOutputStream(outputStream).apply {
                    writeBytes(cmd + "n")
                    flush()
                    writeBytes("exitn")
                    flush()
                }
             
                bufferedReader?.run {
                    while (readLine().also { receive = it } != null) {
                        result.append("n").append(receive)
                    }
                }
               
                waitFor()
            }
        } catch (e: Exception) {
            return false
        }
    
        try {
            dos?.close()
            bufferedReader?.close()
        } catch (e: Exception) {
            return false
        }
    
        return true
    }
}
Cmd().run("pm install -r $basePath/APK/$apkName.apk")//静默安装