天天看點

android 擷取usb 裝置資訊

1.使用者需要擷取usb 裝置名,來判斷是不是我方的列印機

 2.代碼

public String getProductName(){
		byte[] rawDescs = mUsbDeviceConnection.getRawDescriptors();
		String manufacturer = "", product = "";
		try
		{
			byte[] buffer = new byte[255];
			int idxMan = rawDescs[14];
			int idxPrd = rawDescs[15];
			Logger.i("index",idxMan);

			int rdo = mUsbDeviceConnection.controlTransfer(UsbConstants.USB_DIR_IN
							| UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR,
					(LIBUSB_DT_STRING << 8) | idxMan, 0, buffer, 0xFF, 0);
			manufacturer = new String(buffer, 2, rdo - 2, "UTF-16LE");

			rdo = mUsbDeviceConnection.controlTransfer(UsbConstants.USB_DIR_IN
							| UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR,
					(LIBUSB_DT_STRING << 8) | idxPrd, 0, buffer, 0xFF, 0);
			product = new String(buffer, 2, rdo - 2, "UTF-16LE");


		} catch (Exception e)
		{
			e.printStackTrace();
			Logger.e(e.getMessage());
		}

		Logger.i("","Manufacturer:" + manufacturer + "\n");
		Logger.i("","Product:" + product + "\n");
		Logger.i("","Serial#:" + mUsbDeviceConnection.getSerial() + "\n");
		return product.trim()+manufacturer.trim();
	}
           

3.參數含義

android 擷取usb 裝置資訊

 第一 參數常用的就是向裝置寫資料:0xxxxxxx,向裝置讀資料1xxxxxxx.第二是操作哪個結構資料,第三和第四請求不同有不同含義,

第五 資料存放,第六要讀或者寫的資料長度..

 https://blog.csdn.net/obanaganastar/article/details/72866260

4.跟蹤這個方法時 跟到這裡就斷了 是以上面3這個參數我是猜的

int usb_device_control_transfer(struct usb_device *device,
575                            int requestType,
576                            int request,
577                            int value,
578                            int index,
579                            void* buffer,
580                            int length,
581                            unsigned int timeout)
582{
583    struct usbdevfs_ctrltransfer  ctrl;
584
585    // this usually requires read/write permission
586    if (!usb_device_reopen_writeable(device))
587        return -1;
588
589    memset(&ctrl, 0, sizeof(ctrl));
590    ctrl.bRequestType = requestType;
591    ctrl.bRequest = request;
592    ctrl.wValue = value;
593    ctrl.wIndex = index;
594    ctrl.wLength = length;
595    ctrl.data = buffer;
596    ctrl.timeout = timeout;
597    return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
598}
然後調用核心方法
#define USBDEVFS_CONTROL           _IOWR('U', 0, struct usbdevfs_ctrltransfer)
           

5.結果

android 擷取usb 裝置資訊

ps:因為列印機底層的軟體大多是參考愛普生寫,所用可以product 相同 需要用三個拼接在一起比較 .19版本以上才能用UsbDevice 擷取這些資訊. 如果想了解更全可以去下載下傳usb 開發大全 看第四章和第五章.