安卓代码 实现 adb功能/shell语句/dumpsys等

有时候可能需要,在代码中执行一些adb命令,从而实现一些功能,比如pm install安装一些其他软件等。
函数如下:

    private static String exec(String command) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
        final BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
        //这里一定要注意错误流的读取,不然很容易阻塞,得不到你想要的结果,
        final BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        new Thread(new Runnable() {
            String line;
            public void run() {
                String[] info;
                try {
                    while ((line = inputStream.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        int i = 0;
        try {
            i = process.waitFor();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("i=" + i);
        return null;
    }

调用方法示例如下:

exec("dumpsys activity broadcasts");

你可能感兴趣的:(android)