android java代码调用linux命令续

来源:互联网 发布:nginx添加模块 编辑:程序博客网 时间:2024/06/04 22:47

http://blog.csdn.net/dahuaishu2010_/article/details/8494447


 

android java代码调用linux命令续

标签: androidjavalinux
 5553人阅读 评论(0) 收藏 举报
 分类:
 

使用Linux命令首先要获得root,执行命令时记得加上 busybox  。一般我们在用Java IO的基本方法不能把文件放到usb文件,可以用linux命令来做。


ProcessBuilder pb = new ProcessBuilder("/system/bin/sh"); 
//Java.lang.ProcessBuilder:  Creates operating system processes. 
pb.directory(new File("/"));//设置shell的当前目录。   
try {  
    Process proc = pb.start();  
    //获取输入流,可以通过它获取SHELL的输出。   
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
    BufferedReader err = new BufferedReader(new InputStreamReader(proc.getErrorStream())); 
    //获取输出流,可以通过它向SHELL发送命令。   
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc 
                    .getOutputStream())), true);  
    out.println("pwd");  
    out.println("su root");//执行这一句时会弹出对话框(以下程序要求授予最高权限...),要求用户确认。   
    out.println("cd /data/data");//这个目录在系统中要求有root权限才可以访问的。   
    out.println("ls -l");//这个命令如果能列出当前安装的APK的数据文件存放目录,就说明我们有了ROOT权限。   
    out.println("exit");  
    // proc.waitFor();   
    String line;  
    while ((line = in.readLine()) != null) {  
        System.out.println(line);   // 打印输出结果
    }  
    while ((line = err.readLine()) != null) {  
        System.out.println(line);  // 打印错误输出结果
    }  
    in.close();  
    out.close();  
    proc.destroy();  
} catch (Exception e) {  
    System.out.println("exception:" + e);  

 

 

 

 

 

 

 

   File superuser = new File("/system/bin/superuser");  
    
   if (superuser.exists())
   {
    // return device to original state
    Process process = Runtime.getRuntime().exec("superuser");
    DataOutputStream os = new DataOutputStream(process.getOutputStream());    
    os.writeBytes("mount -oremount,rw /dev/block/mtdblock3 /system\n");
    os.writeBytes("busybox cp /system/bin/superuser /system/bin/su\n");
    os.writeBytes("busybox chown 0:0 /system/bin/su\n");
    os.writeBytes("chmod 4755 /system/bin/su\n");
    os.writeBytes("rm /system/bin/superuser\n");
    os.writeBytes("exit\n");
    os.flush();
   }


0 0