方案1:使用Runtime類文章來源:http://www.zghlxwxcb.cn/news/detail-525388.html
/**
* 執(zhí)行命令并且輸出結(jié)果
*/
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;
}
方案二、文章來源地址http://www.zghlxwxcb.cn/news/detail-525388.html
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 { // 經(jīng)過Root處理的android系統(tǒng)即有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")//靜默安裝
到了這里,關于android app代碼中執(zhí)行adb指令的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!