Process 执行Linux命令/调用外部程序

原文地址:http://doublekj.blog.163.com/blog/static/1468184742012118112622509/


 在Java中执行外部程序,是通过java.lang.Runtime对象的exec()方法来完成的。Runtime中重载了6个exec方法,返回一个java.lang.Process对象实例。
这个进程类主要功能是与外部进程通信的,其方法有:
        getInputStream():获取相关进程的输入流
        getOutputStream():获取相关进程的输出流
        waitFor ():等待外部进程执行完,返回进程的出口值
        exitValue ():返回本地进程(native process)的出口值

 下面是一个判断是否取得root权限的例子:

  Process process = null;
  OutputStream out = null;
  int value = -1;
  
  try {
        process = Runtime.getRuntime().exec("su");
        out = process.getOutputStream();
        out.write("exit\n".getBytes());         //Linux命令,注意加上换行符
        out.flush();
        process.waitFor();

        value = process.exitValue();          //value = 0,则有root权限;不等于0,则未取得root权限
  } catch (Exception e) {
        e.printStackTrace();
  } finally {
        try {
              out.close();
        } catch (IOException e) {
        e.printStackTrace();
  }


你可能感兴趣的:(Android)