Android中通过UsbDevice.getDeviceName()返回类似/dev/usb/002/002,不能获取真正的设备名称,
只能通过读取Raw USB Descriptors获取manufacturer名称
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private PendingIntent mPermissionIntent;
protected static final int STD_USB_REQUEST_GET_DESCRIPTOR = 0x06;
protected static final int LIBUSB_DT_STRING = 0x03;
private String getUsbDetail(UsbDevice device) {
String manufacturer = "", product = "", serial = "";
UsbManager manager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
manager.requestPermission(device, mPermissionIntent);
UsbDeviceConnection connection = manager.openDevice(device);
byte[] rawDescs = connection.getRawDescriptors();
try {
byte[] buffer = new byte[255];
int idxMan = rawDescs[14];
int idxPrd = rawDescs[15];
int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_STANDARD,
STD_USB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | idxMan, 0x0409, buffer, 0xFF, 0);
manufacturer = new String(buffer, 2, rdo - 2, "UTF-16LE");
rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_STANDARD,
STD_USB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | idxPrd, 0x0409, buffer, 0xFF, 0);
product = new String(buffer, 2, rdo - 2, "UTF-16LE");
serial = connection.getSerial();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
LogUtils.d("manufacturer:" + manufacturer);
LogUtils.d("product:" + product);
LogUtils.d("serial:" + serial);
return manufacturer;
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
// call method to set up device communication
}
}
else {
txtInfo.append("permission denied for device " + device);
}
}
}
}
};