下面列出了android.hardware.usb.UsbDevice#getInterface ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static UsbHidDevice[] enumerate(Context context, int vid, int pid) throws Exception {
UsbManager usbManager = (UsbManager) context.getApplicationContext().getSystemService(Context.USB_SERVICE);
if (usbManager == null) {
throw new Exception("no usb service");
}
Map<String, UsbDevice> devices = usbManager.getDeviceList();
List<UsbHidDevice> usbHidDevices = new ArrayList<>();
for (UsbDevice device : devices.values()) {
if ((vid == 0 || device.getVendorId() == vid) && (pid == 0 || device.getProductId() == pid)) {
for (int i = 0; i < device.getInterfaceCount(); i++) {
UsbInterface usbInterface = device.getInterface(i);
if (usbInterface.getInterfaceClass() == INTERFACE_CLASS_HID) {
UsbHidDevice hidDevice = new UsbHidDevice(device, usbInterface, usbManager);
usbHidDevices.add(hidDevice);
}
}
}
}
return usbHidDevices.toArray(new UsbHidDevice[usbHidDevices.size()]);
}
UsbTransfer(ResultReceiver resultReceiver, Context context, UsbDevice usbDevice, UsbManager usbManager) throws Exception{
super(resultReceiver, context);
if (usbManager == null) {
finish();
return;
}
usbInterface = usbDevice.getInterface(0);
epIn = usbInterface.getEndpoint(0); // For bulk read
epOut = usbInterface.getEndpoint(1); // For bulk write
deviceConnection = usbManager.openDevice(usbDevice);
if ( ! deviceConnection.claimInterface(usbInterface, false)) {
issueDescription = "USB: failed to claim interface";
throw new Exception("USB: failed to claim interface");
}
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) throws IOException {
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) throw new IOException("Device not connected");
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
for (int i = 0; i < dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
} else {
out = tmpEndpoint;
}
}
connection.claimInterface(dongleInterface, true);
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out);
}
/**
* get interface
* @param interface_id
* @param altsetting
* @return
* @throws IllegalStateException
*/
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting) throws IllegalStateException {
checkConnection();
SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
if (intfs == null) {
intfs = new SparseArray<UsbInterface>();
mInterfaces.put(interface_id, intfs);
}
UsbInterface intf = intfs.get(altsetting);
if (intf == null) {
final UsbDevice device = mWeakDevice.get();
final int n = device.getInterfaceCount();
for (int i = 0; i < n; i++) {
final UsbInterface temp = device.getInterface(i);
if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
intf = temp;
break;
}
}
if (intf != null) {
intfs.append(altsetting, intf);
}
}
return intf;
}
protected void setupUsb(UsbDevice device) {
UsbInterface inf = device.getInterface(0);
UsbDeviceConnection conn = mUsbManager.openDevice(device);
if (conn == null) {
Log.wtf("MainActivity", "unable to open device?");
return;
}
if (!conn.claimInterface(inf, true)) {
conn.close();
Log.wtf("MainActivity", "unable to claim interface!");
return;
}
mBlinkDevice = device;
mBlinkConn = conn;
}
private boolean interfaceMatches(@NonNull final UsbDevice device) {
// if device doesn't match, check the interfaces
final int count = device.getInterfaceCount();
for (int i = 0; i < count; i++) {
final UsbInterface intf = device.getInterface(i);
if (matches(
intf.getInterfaceClass(),
intf.getInterfaceSubclass(),
intf.getInterfaceProtocol())) {
return true;
}
if (interfaceMatches(
intf.getInterfaceClass(),
intf.getInterfaceSubclass(),
intf.getInterfaceProtocol())) {
return true;
}
}
return false;
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
return null;
}
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE) || (device.getProductId() == PID_NANOX));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
/**
* 指定したUsbDeviceがこのDeviceFilterにマッチするかどうかを返す
* mExcludeフラグは別途#isExcludeか自前でチェックすること
* @param device
* @return
*/
public boolean matches(final UsbDevice device) {
if (mVendorId != -1 && device.getVendorId() != mVendorId) {
return false;
}
if (mProductId != -1 && device.getProductId() != mProductId) {
return false;
}
/* if (mManufacturerName != null && device.getManufacturerName() == null)
return false;
if (mProductName != null && device.getProductName() == null)
return false;
if (mSerialNumber != null && device.getSerialNumber() == null)
return false;
if (mManufacturerName != null && device.getManufacturerName() != null
&& !mManufacturerName.equals(device.getManufacturerName()))
return false;
if (mProductName != null && device.getProductName() != null
&& !mProductName.equals(device.getProductName()))
return false;
if (mSerialNumber != null && device.getSerialNumber() != null
&& !mSerialNumber.equals(device.getSerialNumber()))
return false; */
// check device class/subclass/protocol
if (matches(device.getDeviceClass(), device.getDeviceSubclass(), device.getDeviceProtocol())) {
return true;
}
// if device doesn't match, check the interfaces
final int count = device.getInterfaceCount();
for (int i = 0; i < count; i++) {
final UsbInterface intf = device.getInterface(i);
if (matches(intf.getInterfaceClass(), intf.getInterfaceSubclass(), intf.getInterfaceProtocol())) {
return true;
}
}
return false;
}
public PL2303SerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
{
super(device, connection);
if (iface > 1)
{
throw new IllegalArgumentException("Multi-interface PL2303 devices not supported!");
}
mInterface = device.getInterface(iface >= 0 ? iface : 0);
}
/**
* 指定したUsbDeviceがこのDeviceFilterにマッチするかどうかを返す
* mExcludeフラグは別途#isExcludeか自前でチェックすること
* @param device
* @return
*/
public boolean matches(final UsbDevice device) {
if (mVendorId != -1 && device.getVendorId() != mVendorId) {
return false;
}
if (mProductId != -1 && device.getProductId() != mProductId) {
return false;
}
/* if (mManufacturerName != null && device.getManufacturerName() == null)
return false;
if (mProductName != null && device.getProductName() == null)
return false;
if (mSerialNumber != null && device.getSerialNumber() == null)
return false;
if (mManufacturerName != null && device.getManufacturerName() != null
&& !mManufacturerName.equals(device.getManufacturerName()))
return false;
if (mProductName != null && device.getProductName() != null
&& !mProductName.equals(device.getProductName()))
return false;
if (mSerialNumber != null && device.getSerialNumber() != null
&& !mSerialNumber.equals(device.getSerialNumber()))
return false; */
// check device class/subclass/protocol
if (matches(device.getDeviceClass(), device.getDeviceSubclass(), device.getDeviceProtocol())) {
return true;
}
// if device doesn't match, check the interfaces
final int count = device.getInterfaceCount();
for (int i = 0; i < count; i++) {
final UsbInterface intf = device.getInterface(i);
if (matches(intf.getInterfaceClass(), intf.getInterfaceSubclass(), intf.getInterfaceProtocol())) {
return true;
}
}
return false;
}
public static boolean isCdcDevice(UsbDevice device)
{
int iIndex = device.getInterfaceCount();
for(int i=0;i<=iIndex-1;i++)
{
UsbInterface iface = device.getInterface(i);
if(iface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA)
return true;
}
return false;
}
@SuppressLint("NewApi")
public DeviceFilter(@NonNull final UsbDevice device, final boolean isExclude) {
mVendorId = device.getVendorId();
mProductId = device.getProductId();
mClass = device.getDeviceClass();
mSubclass = device.getDeviceSubclass();
mProtocol = device.getDeviceProtocol();
// getInterfaceCountは内部配列のlengthを返すので負にはならないはずだけど年のために下限を0にする
final int count = Math.max(device.getInterfaceCount(), 0);
mIntfClass = new int[count];
mIntfSubClass = new int[count];
mIntfProtocol = new int[count];
for (int i = 0; i < count; i++) {
final UsbInterface intf = device.getInterface(i);
mIntfClass[i] = intf.getInterfaceClass();
mIntfSubClass[i] = intf.getInterfaceSubclass();
mIntfProtocol[i] = intf.getInterfaceProtocol();
}
if (BuildCheck.isLollipop()) {
mManufacturerName = device.getManufacturerName();
mProductName = device.getProductName();
mSerialNumber = device.getSerialNumber();
} else {
mManufacturerName = null;
mProductName = null;
mSerialNumber = null;
}
this.isExclude = isExclude;
}
/**
* インターフェースを取得する
* @param interface_id
* @param altsetting
* @return
* @throws IllegalStateException
*/
@SuppressLint("NewApi")
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting)
throws IllegalStateException {
checkConnection();
SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
if (intfs == null) {
intfs = new SparseArray<UsbInterface>();
mInterfaces.put(interface_id, intfs);
}
UsbInterface intf = intfs.get(altsetting);
if (intf == null) {
final UsbDevice device = mWeakDevice.get();
final int n = device.getInterfaceCount();
for (int i = 0; i < n; i++) {
final UsbInterface temp = device.getInterface(i);
if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
intf = temp;
break;
}
}
if (intf != null) {
intfs.append(altsetting, intf);
}
}
return intf;
}
public static Trezor getDevice(final Context context) {
final UsbManager manager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
for (final UsbDevice device: manager.getDeviceList().values()) {
// Check if the device is TREZOR (or AvalonWallet or BWALLET)
final int vendorId = device.getVendorId();
final int productId = device.getProductId();
if ((vendorId != 0x534c || productId != 0x0001) &&
(vendorId != 0x1209 || productId != 0x53c0) &&
(vendorId != 0x1209 || productId != 0x53c1) &&
(vendorId != 0x10c4 || productId != 0xea80)) {
continue;
}
Log.d(TAG, "Hardware Wallet device found");
if (device.getInterfaceCount() < 1) {
Log.e(TAG, "Wrong interface count");
continue;
}
// Use first interface
final UsbInterface iface = device.getInterface(0);
// Try to find read/write endpoints
UsbEndpoint readEndpoint = null, writeEndpoint = null;
for (int i = 0; i < iface.getEndpointCount(); ++i) {
final UsbEndpoint ep = iface.getEndpoint(i);
if (readEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
ep.getAddress() == 0x81) {
// number = 1 ; dir = USB_DIR_IN
readEndpoint = ep;
continue;
}
if (writeEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
(ep.getAddress() == 0x01 || ep.getAddress() == 0x02)) {
// number = 1 ; dir = USB_DIR_OUT
writeEndpoint = ep;
continue;
}
Log.d(TAG, String.format("ep %d", ep.getAddress()));
}
if (isEndpointBad(readEndpoint, "read") || isEndpointBad(writeEndpoint, "write"))
continue;
// Try to open the device
final UsbDeviceConnection conn = manager.openDevice(device);
if (conn == null || !conn.claimInterface(iface, true)) {
Log.e(TAG, conn == null ? "Could not open connection" : "Could not claim interface");
continue;
}
// All OK - return the class
return new Trezor(device, conn, readEndpoint, writeEndpoint);
}
return null;
}
public static boolean OpenAdapter()
{
// If the adapter is already open. Don't attempt to do it again
if (usb_con != null && usb_con.getFileDescriptor() != -1)
return true;
HashMap<String, UsbDevice> devices = manager.getDeviceList();
for (Map.Entry<String, UsbDevice> pair : devices.entrySet())
{
UsbDevice dev = pair.getValue();
if (dev.getProductId() == NINTENDO_WIIMOTE_PRODUCT_ID &&
dev.getVendorId() == NINTENDO_VENDOR_ID)
{
if (manager.hasPermission(dev))
{
usb_con = manager.openDevice(dev);
UsbConfiguration conf = dev.getConfiguration(0);
Log.info("Number of configurations: " + dev.getConfigurationCount());
Log.info("Number of Interfaces: " + dev.getInterfaceCount());
Log.info("Number of Interfaces from conf: " + conf.getInterfaceCount());
// Sometimes the interface count is returned as zero.
// Means the device needs to be unplugged and plugged back in again
if (dev.getInterfaceCount() > 0)
{
for (int i = 0; i < MAX_WIIMOTES; ++i)
{
// One interface per Wii Remote
usb_intf[i] = dev.getInterface(i);
usb_con.claimInterface(usb_intf[i], true);
// One endpoint per Wii Remote. Input only
// Output reports go through the control channel.
usb_in[i] = usb_intf[i].getEndpoint(0);
Log.info("Interface " + i + " endpoint count:" + usb_intf[i].getEndpointCount());
}
return true;
}
else
{
// XXX: Message that the device was found, but it needs to be unplugged and plugged back in?
usb_con.close();
}
}
}
}
return false;
}
private UsbDeviceInfo getInfoForDevice(UsbDevice dev, UsbDeviceConnection devConn) {
UsbDeviceInfo info = new UsbDeviceInfo();
UsbIpDevice ipDev = new UsbIpDevice();
ipDev.path = dev.getDeviceName();
ipDev.busnum = deviceIdToBusNum(dev.getDeviceId());
ipDev.devnum = deviceIdToDevNum(dev.getDeviceId());
ipDev.busid = String.format("%d-%d", ipDev.busnum, ipDev.devnum);
ipDev.idVendor = (short) dev.getVendorId();
ipDev.idProduct = (short) dev.getProductId();
ipDev.bcdDevice = -1;
ipDev.bDeviceClass = (byte) dev.getDeviceClass();
ipDev.bDeviceSubClass = (byte) dev.getDeviceSubclass();
ipDev.bDeviceProtocol = (byte) dev.getDeviceProtocol();
ipDev.bConfigurationValue = 0;
ipDev.bNumConfigurations = 1;
ipDev.bNumInterfaces = (byte) dev.getInterfaceCount();
info.dev = ipDev;
info.interfaces = new UsbIpInterface[ipDev.bNumInterfaces];
for (int i = 0; i < ipDev.bNumInterfaces; i++) {
info.interfaces[i] = new UsbIpInterface();
UsbInterface iface = dev.getInterface(i);
info.interfaces[i].bInterfaceClass = (byte) iface.getInterfaceClass();
info.interfaces[i].bInterfaceSubClass = (byte) iface.getInterfaceSubclass();
info.interfaces[i].bInterfaceProtocol = (byte) iface.getInterfaceProtocol();
}
AttachedDeviceContext context = connections.get(dev.getDeviceId());
UsbDeviceDescriptor devDesc = null;
if (context != null) {
// Since we're attached already, we can directly query the USB descriptors
// to fill some information that Android's USB API doesn't expose
devDesc = UsbControlHelper.readDeviceDescriptor(context.devConn);
ipDev.bcdDevice = devDesc.bcdDevice;
ipDev.bNumConfigurations = devDesc.bNumConfigurations;
}
ipDev.speed = detectSpeed(dev, devDesc);
return info;
}
public static Trezor getDevice(final Context context, final TrezorGUICallback guiFn,
final Network network) {
final UsbManager manager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
for (final UsbDevice device: manager.getDeviceList().values()) {
// Check if the device is TREZOR (or AvalonWallet or BWALLET)
final int vendorId = device.getVendorId();
final int productId = device.getProductId();
if ((vendorId != 0x534c || productId != 0x0001) &&
(vendorId != 0x1209 || productId != 0x53c0) &&
(vendorId != 0x1209 || productId != 0x53c1) &&
(vendorId != 0x10c4 || productId != 0xea80)) {
continue;
}
Log.i(TAG, "Hardware Wallet device found");
if (device.getInterfaceCount() < 1) {
Log.e(TAG, "Wrong interface count");
continue;
}
// Use first interface
final UsbInterface iface = device.getInterface(0);
// Try to find read/write endpoints
UsbEndpoint readEndpoint = null, writeEndpoint = null;
for (int i = 0; i < iface.getEndpointCount(); ++i) {
final UsbEndpoint ep = iface.getEndpoint(i);
if (readEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
ep.getAddress() == 0x81) {
// number = 1 ; dir = USB_DIR_IN
readEndpoint = ep;
continue;
}
if (writeEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
(ep.getAddress() == 0x01 || ep.getAddress() == 0x02)) {
// number = 1 ; dir = USB_DIR_OUT
writeEndpoint = ep;
continue;
}
Log.e(TAG, String.format("ep %d", ep.getAddress()));
}
if (!isEndpointOK(readEndpoint, "read") || !isEndpointOK(writeEndpoint, "write"))
continue;
// Try to open the device
final UsbDeviceConnection conn = manager.openDevice(device);
if (conn == null || !conn.claimInterface(iface, true)) {
Log.e(TAG, conn == null ? "Could not open connection" : "Could not claim interface");
continue;
}
// All OK - return the class
return new Trezor(guiFn, device, conn, readEndpoint, writeEndpoint, network);
}
return null;
}
@Deprecated
public BLED112SerialDevice(UsbDevice device, UsbDeviceConnection connection)
{
super(device, connection);
mInterface = device.getInterface(1); // BLED112 Interface 0: Communications | Interface 1: CDC Data
}
public CDCSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
{
super(device, connection);
mInterface = device.getInterface(iface >= 0 ? iface : findFirstCDC(device));
}
public CP2130SpiDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
{
super(device, connection);
mInterface = device.getInterface(iface >= 0 ? iface : 0);
currentChannel = 0;
}