1.使用UsbManager檢測設備是否連接

if(usbManager == null) {
// 獲取USB Manager
usbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
}
        // 獲取所有USB設備
        Map<String, UsbDevice> deviceList = usbManager.getDeviceList();
        // 查找設備
        for (Map.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
            UsbDevice device = entry.getValue();
            int venId = device.getVendorId();
            int proId = device.getProductId();
            String name = device.getDeviceName();
            Log.d(TAG,"vendor id:"+ venId + ", product id:" + proId + ", name:"+name);
            if(venId == vendorId && proId == productId){ //vendorId,productId指定的usb設備id
               usbDevice = device; //獲取需要讀取的usb設備
               break;
            }
        }

2.使用UsbManager和UsbDevice讀取數據

獲取usbEndpoint

        if(usbManager == null || usbDevice == null){
            return;
        }
        // 3. 打開設備連接
        connection = usbManager.openDevice(usbDevice);

        // 4. 找到正確的接口和端點
        usbInterface = usbDevice.getInterface(0); // 假設我們要使用的接口是第0個
        boolean interfaceClaimed = connection.claimInterface(usbInterface, true);

        if (interfaceClaimed) {
            // 接口已成功聲明
            endpointIn = usbInterface.getEndpoint(0); // 假設輸入端點是第0個
        }

使用線程循環讀取

        new Thread(() -> {
            while (!isStopReadData && endpointIn != null) {
                // 5. 使用UsbDeviceConnection進行讀寫
                byte[] buffer = new byte[14]; // 數據緩衝區
                int readCount = connection.bulkTransfer(endpointIn, buffer, buffer.length, 0);
                if (readCount > 0) {
                    // 成功讀取數據,buffer的前readCount字節現在包含從設備讀取的數據
                    mCurrentData = bytes2Hex(buffer);
                }else {
                    mCurrentData = null;
                }
                try {
                    Thread.sleep(mIntervalReadTime);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

將讀取的數據轉換16進制數

    private String bytes2Hex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }


3.停止讀取並釋放

釋放資源

        isStopReadData = true;
        // 釋放接口
        connection.releaseInterface(usbInterface);
        // 關閉設備連接
        connection.close();
        connection = null;