Android USB Create Connection 完整过程

来源:互联网 发布:女生都穿安全裤 知乎 编辑:程序博客网 时间:2024/06/03 17:28
  private void connect2Usb() {        Logger.t(TAG).d("connect2Usb : connect");        // 1 获取Usbmanager        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);        // 2 获取UsbDevice        HashMap<String, UsbDevice> usbDevices = mUsbManager.getDeviceList();        // 3 遍历UsbDevices, 查找USB Device        Set<Map.Entry<String, UsbDevice>> entrySet = usbDevices.entrySet();        UsbDevice usbDevice= null;        for (Map.Entry<String, UsbDevice> entry : entrySet) {            Logger.t(TAG).d("connect2Usb : " + entry.getKey() + "," + entry.getValue());            //find your usb device            if (entry.getValue().getVendorId() == USB_VENDORID) {                usbDevice= entry.getValue();                break;            }        }        if (usbDevice== null) {            Logger.t(TAG).e("no usb devices");            return;        }        if (usbDevice.getInterfaceCount() <= 0) {            Logger.t(TAG).e("no usb devices interface ");            return;        }        //[4] 查找Usb Interface        mUsbInterface = usbDevice.getInterface(0);        Logger.t(TAG).d("usb interface : " + mUsbInterface);        //[5] 查找 Endpoints        for (int i = 0; i < mUsbInterface.getEndpointCount(); i++) {            UsbEndpoint endpoint = mUsbInterface.getEndpoint(i);            if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {                mUsbEndpointIn = endpoint;                if (mUsbEndpointIn.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {                    Logger.t(TAG).d("usb bulk transfer");                }            }            if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {                mUsbEndpointOut = endpoint;            }            //for test            int direction = endpoint.getDirection();            Logger.d("direction " + direction);        }        // [5] 检查usb权限        boolean hasPermission = mUsbManager.hasPermission(usbDevice);        if (!hasPermission) {            Logger.t(TAG).e("no usb permission");            //[7] 申请usb权限            PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 9898, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_ONE_SHOT);            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);            registerReceiver(mUsbReceiver, filter);            mUsbManager.requestPermission(usbDevice, mPermissionIntent);            return;        }        //[8] Open usb Device, create connection        if (mUsbDeviceConnection == null) {            mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);        }        //[9] claim UsbInterface        if (mUsbDeviceConnection != null) {            boolean claimUsb = mUsbDeviceConnection.claimInterface(mUsbInterface, true);            if (claimUsb) {                Logger.t(TAG).d("claimed usbinterface");            }        }        //开始USB Communication。        //...    }