java determined whether the PC is connected to the mobile device via Adb

Recently used PC and the mobile terminal through the USB connection to transfer data, thus always using Adb command codes for fault tolerance and strict logic, like the data prior to transmission, PC and mobile terminal to establish a session, to prevent the movable terminal not connected directly transfer data being given, to find such methods for a long time did not find, then himself Adb implement this method in the code inside through. For your reference, we welcome a better way to achieve more exchanges.

Directly on the code

    /**
     * @Description: 判断是否连接设备
     * @Param: []
     * @return: boolean  
     * @Author: Mengw9
     */
    public static boolean isLinkDevices(){
        String str = this.adbCmd("D:\adb\adb devices");
        assert str != null;
        str = str.replaceAll("List of devices attached", "").replaceAll("\n", "");
        if (!str.isEmpty()){
            System.out.println("已连接设备,设备名为:"+str);
            return true;
        }
        System.out.println("未连接设备");
        return false;
    }

    /**
     * @Description: 执行cmd命令
     * @Param: [cmd]
     * @return: void
     * @Author: Mengw9
     */
    public static String adbCmd(String cmd){
        Process process;
        try {
            process=Runtime.getRuntime().exec(cmd);
            System.out.println(inputStream2String(process.getInputStream()));
            return inputStream2String(process.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description: 返回流处理成字符串
     * @Param: [inputStream]
     * @return: java.lang.String
     * @Author: Mengw9
     */
    private static String inputStream2String(InputStream inputStream){
        String result="";
        BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
        try {
            String temp="";
            while ((temp=br.readLine())!=null){
                result+=temp+"\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

Use this code needs to have adb driver download locally, I was directly on the D drive

adb drivers share https://www.lanzous.com/b0bk4wlpe Password: 8uz5

Other learning Adb command link:

Adb commonly used commands

Detailed installation Adb

Guess you like

Origin www.cnblogs.com/mengw/p/12073079.html