红联Linux门户
Linux帮助

Android执行Linux命令的方法:提示Java.io.IOException

发布时间:2017-01-12 10:36:12来源:linux网站作者:yanjiee
一开始使用的是这样的方法:
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;  
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/27739.html