Android: how to detect an already connected USB device?

I am trying to detect USB devices that are already connected to Android. I understand there are actions to detect when USB is plugged in or unplugged. But I really don't understand how to check devices after connecting USB device to Android. Also, I found that every USB device has a device class code, but how can I tell which device is connected? For example, I need to detect a usb mouse and keyboard; how to distinguish them?

+3


source to share


2 answers


Try the following:

  • First Broadcast register for USB connection. manifest resolution:

:



<intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter>

      

  1. Get a list of USB devices with detailed information using this

    public void getDetail() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
        UsbDevice device = deviceIterator.next();
    
        manager.requestPermission(device, mPermissionIntent);
        String Model = device.getDeviceName();
    
        int DeviceID = device.getDeviceId();
        int Vendor = device.getVendorId();
        int Product = device.getProductId();
        int Class = device.getDeviceClass();
        int Subclass = device.getDeviceSubclass();
    
    }}
    
          

+4


source


Just to answer Benny's question, here's what mPermissionIntent might look like:



string actionString = context.PackageName + ".action.USB_PERMISSION";

PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(context, 0, new 
Intent(actionString), 0);
mUsbManager.RequestPermission(device, permissionIntent);

      

0


source







All Articles