android中调用shell命令一般通过这就是Runtime类,在Runtime类里提供了获取当前运行环境的接口。
其中的exec函数返回一个执行shell命令的子进程。exec函数的具体实现形式有以下几种:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException
1)执行简单的命令的方法:
代码如下:
try
String commands = "ls -l";
Process process = Runtime.getRuntime().exec (commands);
// for showing the info on screen
InputStreamReader ir=new
InputStreamReader(process.getInputStream());
BufferedReader input = new BufferedReader (ir);
String line;
while ((line = input.readLine ()) != null){
System.out.println(line);
}//end try
catch (java.io.IOException e){
System.err.println ("IOException " + e.getMessage());
}
2)执行带有参数的命令(尤其是参数需要用引号的)时则需要用String的数组来表示整个命令,而且要用转义符把引号的特殊含义去除,例如我们要执行
find / -name "*mysql*" -print 时,用如下代码
try
String[] commands = new
String[]{"find","