方案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("exit\n") 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")//静默安装
来源地址:https://blog.csdn.net/liuqinhou/article/details/129168130