android - 在 Android Studio 上运行终端命令
问题描述
我正在尝试制作一个允许我切换手机缩放调节器的应用程序(是的,我已经扎根了)。经过大量搜索,我发现我通常需要运行命令关闭process = Runtime.getRuntime().exec(cmd);
但是,经过多次尝试,该应用程序似乎没有正确响应。到目前为止,这是我的代码。
String RunCommand(String cmd) {
StringBuffer cmdOut = new StringBuffer();
Process process;
try{
process = Runtime.getRuntime().exec(cmd);
InputStreamReader r = new InputStreamReader(process.getInputStream());
BufferedReader bufReader = new BufferedReader(r);
char[] buf = new char[4096];
int nRead = 0;
while ((nRead = bufReader.read(buf)) > 0){
cmdOut.append(buf, 0, nRead);
}
bufReader.close();
try {
process.waitFor();
}catch (InterruptedException e){
e.printStackTrace();
}
}catch (IOException e) {
e.printStackTrace();
}
return cmdOut.toString();
}
事实上,我不需要输出文件,因为我正在运行的命令实际上并不需要输出。IEecho performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
当我运行该应用程序时,它要么挂起,要么什么都不做。不知道我做错了什么?非常感谢任何帮助!
解决方案
这是我用于我的应用程序的代码:
fun sudo(vararg strings: String) {
try {
val su = Runtime.getRuntime().exec("su")
val outputStream = DataOutputStream(su.outputStream)
for (s in strings) {
outputStream.writeBytes(s + "\n")
outputStream.flush()
}
outputStream.writeBytes("exit\n")
outputStream.flush()
try {
su.waitFor()
} catch (e: InterruptedException) {
e.printStackTrace()
}
outputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
它在 Kotlin 中,但很容易转换为 Java。
我相信,关键部分是exec()
用su
. 然后,该函数将您发送的命令写入 OutputStream,以便在su
进程下运行它们。
如果您的应用程序挂起,请确保您使用您使用的任何管理器(Magisk、SuperSU 等)授予它 root 访问权限。
推荐阅读
- javascript - 在新选项卡上保留输入值
- git - Error while evaluating a Resource Statement, Unknown resource type: 'vcsrepo'
- google-chrome - Firefox 搞砸了 SVG 使用/定义
- python - Python:如何将两个嵌套列表合并为一个嵌套列表
- mysql - 从仅存在于其中一个表中的多个表中选择一行
- java - 如何检查我的所有文本字段是否为空 JavaFX
- numpy - 两个矩阵的所有列组合的分量乘积
- r - 带有 R 3.6 的 Ubuntu 19.04 - 无法安装 R Shiny 包?
- google-apps-script - 从自定义菜单中找不到脚本
- c# - 在条件中重新声明模式匹配变量的 C# 错误