Android执行Linux命令的方法
2016-05-17 11:08
459 查看
一开始使用的是这样的方法:
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;
}
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;
}
相关文章推荐
- Linux crontab定时执行任务
- Linux 性能监控、测试、优化工具
- CentOS 7 时区设置
- Linux下修改MySQL数据库字符编码为UTF-8解决中文乱码
- python修改linux日志(logtamper.py)
- linux socket的connect 超时
- linux chmod命令
- Linux服务器Cache占用过多内存导致系统内存不足问题的排查解决
- linux find命令-exec参数使用说明
- java在linux系统下文件夹出现中文乱码的问题
- linux安装-版本选择-终极决定
- Linux,Unix各种版本的操作系统在线安装软件命令
- Linux系统下Mysql使用简单教程(一)
- CentOS7 设置截图的快捷键
- linux中 777,755等用户权限说明
- 阿里云Centos配置iptables防火墙
- Linux基础之Linux简介
- Linux errno 错误对照表
- Linux下设置帧和socket缓冲区的大小
- linux中eth0原何变成了eth1