在Android Studio上运行终端命令
我正在尝试制作一个应用程序,允许我切换我手机的缩放控制器(是的,我是根)。经过多次搜索,我发现我通常需要在在Android Studio上运行终端命令,android,shell,android-studio,terminal,runtime.exec,Android,Shell,Android Studio,Terminal,Runtime.exec,我正在尝试制作一个应用程序,允许我切换我手机的缩放控制器(是的,我是根)。经过多次搜索,我发现我通常需要在process=Runtime.getRuntime().exec(cmd)下运行命令 然而,经过多次尝试,该应用程序似乎没有正确响应。这是到目前为止我的代码 String RunCommand(String cmd) { StringBuffer cmdOut = new StringBuffer(); Process process; try{
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();
}
事实上,我不需要输出文件,因为我运行的命令实际上不需要输出。i、 eecho性能>/sys/devices/system/cpu/cpu0/cpufreq/scaling\u调控器
当我运行应用程序时,它要么挂起,要么什么都不做。不知道我做错了什么?非常感谢您的帮助 这是我在应用程序中使用的代码:
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
我认为,关键部分是使用su
启动新流程(exec()
)。然后,该函数将您发送的命令写入OutputStream,以便在su
进程下运行这些命令
如果您的应用程序挂起,请确保您正在使用任何管理器(Magisk、SuperSU等)授予它root访问权限。谢谢您的帮助!还有一件事,DataOutputStream通常用于输入终端命令(对于我的用例),DataInputStream用于从终端获取结果(如果有的话),这样说对吗?或者我可以用这样的方法来计算结果吗?“BufferedReader=new BufferedReader(new InputStreamReader(process.getInputStream()));”@NicholasKoh yes