自动化ADB SHELL

来源:互联网 发布:菠菜源码架设视频教程 编辑:程序博客网 时间:2024/06/07 05:24
  1. import java.io.InputStream;    
  2. import java.io.OutputStream;    
  3. import java.io.IOException;    
  4.     
  5. public class AndroidShell  {    
  6.    private ProcessBuilder builder;    
  7.    private Process adb;    
  8.    private static final byte[] LS = "/n".getBytes();    
  9.     
  10.    private OutputStream processInput;    
  11.    private InputStream processOutput;    
  12.     
  13.    private Thread t;    
  14.     
  15.    /**   
  16.     * Starts the shell    
  17.     */    
  18.    public void start() throws IOException  {    
  19.       builder = new ProcessBuilder("adb""shell");    
  20.       adb = builder.start();    
  21.     
  22.       // reads from the process output    
  23.       processInput = adb.getOutputStream();    
  24.     
  25.       // sends to process's input    
  26.       processOutput = adb.getInputStream();    
  27.     
  28.       // thread that reads process's output and prints it to system.out    
  29.       Thread t = new Thread() {    
  30.          public void run() {    
  31.             try   {    
  32.                int c = 0;    
  33.                byte[] buffer = new byte[2048];    
  34.                while((c = processOutput.read(buffer)) != -1) {    
  35.                      System.out.write(buffer, 0, c);    
  36.                }    
  37.             }catch(Exception e)  {}    
  38.          }    
  39.       };    
  40.       t.start();    
  41.    }    
  42.     
  43.    /**   
  44.     * Stop the shell;   
  45.     */    
  46.    public void stop()   {    
  47.       try   {    
  48.          if(processOutput != null && t != null) {    
  49.             this.execCommand("exit");    
  50.             processOutput.close();    
  51.          }    
  52.       }catch(Exception ignore)  {}    
  53.    }    
  54.     
  55.    
  56.       public void execCommand(String adbCommand) throws IOException {    
  57.       processInput.write(adbCommand.getBytes());    
  58.       processInput.write(LS);    
  59.       processInput.flush();    
  60.    }    
  61.     
  62.    public static void main(String[] args) throws Exception  {    
  63.       AndroidShell shell = new AndroidShell();    
  64.       shell.start();    
  65.       shell.execCommand("input keyevent '3' ");//HOME
  66.            
  67.       shell.stop();    
  68.    }    
  69. }   
原创粉丝点击