process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。
process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。
至于详细的process类的介绍放在以后介绍。
另外还要注意一个类:Runtime类,Runtime类是一个与JVM运行时环境有关的类,这个类是Singleton的。
这里用到的Runtime.getRuntime()方法是取得当前JVM的运行环境,也是java中唯一可以得到运行环境的方法。(另外,Runtime的大部分方法都是实例方法,也就是说每次运行调用的时候都需要调用到getRuntime方法)
下面说说Runtime的exec()方法,这里要注意的有一点,就是public Process exec(String [] cmdArray,
String []
envp);这个方法中cmdArray是一个执行的命令和参数的字符串数组,数组的第一个元素是要执行的命令往后依次都是命令的参数,envp感觉应该
和C中的execve中的环境变量是一样的,envp中使用的是name=value的方式。
public boolean
runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process =
Runtime.getRuntime().exec("su");
os = new
DataOutputStream(process.getOutputStream());
os.writeBytes(command+"\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
//
Log.d(TAG, "the device is not rooted, error message: " +
e.getMessage());
DisplayToast("the device is not rooted,
error message: " + e.getMessage());
return false;
} finally {
try {
if (os != null)
{
os.close();
}
if(process != null) {
process.destroy();
}
} catch (Exception e)
{
e.printStackTrace();
}
}
return true;
}