Android : how to detect already connected usb device?

后端 未结 3 954
庸人自扰
庸人自扰 2020-12-09 23:22

I\'m trying to detect usb devices which are already connected to android. I understand there are actions to detect when USB is either attached or detached. But I don\'t rea

相关标签:
3条回答
  • 2020-12-09 23:32

    Try this:

    1. First register Broadcast for USB connection. manifest permission:

    :

    <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter>
    
    1. Get the List of USB Device with details by 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();
      
      }}
      
    0 讨论(0)
  • 2020-12-09 23:41

    The answer from "Christopher Garza" is probably in Kotlin. I'll send you the code but in Java.

    String actionString = getApplicationContext().getPackageName() + ".action.USB_PERMISSION";
    
    PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new
                    Intent(actionString), 0);
    

    You can remove "getApplicationContext()" if you are pasting this code in an Activity. Otherwise if you are pasting this in other class not specified with an Activity, then you need some sort of this code:

    public class Example {
        private Context context;
    
        public Example(Context context) {
            this.context = context;
        }
    }
    
    0 讨论(0)
  • 2020-12-09 23:47

    Just to answer Benny's question here is what the mPermissionIntent could look like:

    string actionString = context.PackageName + ".action.USB_PERMISSION";
    
    PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(context, 0, new 
    Intent(actionString), 0);
    mUsbManager.RequestPermission(device, permissionIntent);
    
    0 讨论(0)
提交回复
热议问题