背景:在某些情况下,比如修改以太网IP地址、修改系统时间等等、使用ADB指令直接执行会方便很多,缺点就是有时候需要Root权限。但如果是做工业设备开发的,本身就具有权限的情况下就完全没问题了(比如我)。
一、核心代码
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 {
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")