3

My application uses UsbManager to communicate with USB cameras. Some devices don't have USB support. These will return null for (UsbManager)context.getSystemService( Context.USB_SERVICE ), or they will throw a NoSuchMethodError exception when enumerating devices. I can detect both and display a message properly. Unfortunately, some Androids that don't detect USB devices cause neither of these problems. They just return an empty list of USB devices. How can I properly detect that this system doesn't support USB OTG?

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • Have you tried using `android.hardware.usb.host` with `` or `PackageManager` and `hasSystemFeature()`? – CommonsWare May 29 '14 at 13:20
  • @CommonsWare: `if (!context.getPackageManager().hasSystemFeature("android.hardware.usb.host"))` works, thanks a lot! Please make it an answer. – Violet Giraffe May 29 '14 at 13:30

2 Answers2

7

The official way to determine if the device has USB host capability is to use the associated system feature.

Ideally, add a <uses-feature> element to your manifest, indicating that you are interested in the android.hardware.usb.host feature. If you do not absolutely need that feature, add android:required="false" as an attribute.

If you went with android:required="false", and you want to determine whether the device is a USB host at runtime, use PackageManager, hasSystemFeature(), and FEATURE_USB_HOST. FEATURE_USB_HOST is defined as the same string as you would be using in <uses-feature> (android.hardware.usb.host).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I have samsung galaxy s3 neo (http://www.gsmarena.com/samsung_i9300i_galaxy_s3_neo-6289.php) This phone does not support OTG, but FEATURE_USB_HOST returns true. – Muno Jul 03 '16 at 12:51
  • Some phones have the option to enable/disable OTG from settings. How can I know that status? The phone has the OTG support and it is disabled in Settings. – Zacharias Manuel Oct 24 '19 at 10:05
  • @ZachariasManuel: I am not aware of any documented and supported way to determine that. My guess is that this is something specific to that device manufacturer, and therefore it would be up to that device manufacturer to tell you if there is a way to detect the setting's state. – CommonsWare Oct 24 '19 at 11:11
0
public static boolean getUsbConnection(Context context) {
        intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
        return intent.getExtras().getBoolean("connected");
    }
Lucian Novac
  • 1,255
  • 12
  • 18