一开始使用的是这样的方法:
Runtime.getRuntime().exec("echo default-on > /sys/class/leds/firefly:yellow:user/trigger");后来发现一直出现错误,主要提示:
Working Directory: null Environment: null
和
java.io.IOException: Permission denied
然后一开始我以为是权限不行,就把APK放到/system/app下,还是提示这样的错误。
我又就尝试了
Runtime.getRuntime().exec("ls");发现ls和ps这类在/system/bin下面存在的命令,都是可以正确执行的,而cd,cat这类的bash命令都是提示上面的错误。
辗转反侧终于找到了方法:
String[] cmdline = { "sh", "-c", cmd};
Process p = Runtime.getRuntime().exec("echo default-on > /sys/class/leds/firefly:yellow:user/trigger");完整的函数贴出来:
// 执行命令
public static String do_exec(String cmd) {
String s = "\n";
try {
String[] cmdline = { "sh", "-c", cmd};
Process p = Runtime.getRuntime().exec(cmdline);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(p.getOutputStream())), true);
//out.println(cmd);
while ((line = in.readLine()) != null) {
s += line + "\n";
}
in.close();
// out.close();
Log.v(TAG, s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// text.setText(s);
return s;
}
本文介绍了一种在Android系统上通过Java代码执行Shell命令的方法,并解决了执行特定命令时遇到的权限问题。文章详细说明了如何使用Runtime类执行ls等命令,以及如何通过调用sh来执行如echo等命令。

479

被折叠的 条评论
为什么被折叠?



