NullPointerException from UsbManager

I have a code that looks like

UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE); usbManager.getDeviceList(); 

When I use the Android 5.0 emulator, I get this crash:

 java.lang.NullPointerException: Attempt to invoke interface method 'void android.hardware.usb.IUsbManager.getDeviceList(android.os.Bundle)' on a null object reference at android.hardware.usb.UsbManager.getDeviceList(UsbManager.java:243) ... 

I understand that the official Android emulator does not support USB, but I expect to see an empty list of USB devices, not a crash.

I was a little determined in the Android code, and the ServiceManager the services map did not have an entry for "usb" . Nothing in the Android 21 stack handles the null value returned by the ServiceManager .

The code works fine on emulated 4.4 devices, but crashes on 5.0 devices. The processor architecture does not seem to matter; I tried ARM and x86.

It also works great on all the Genymotion devices I've tried, but I need this to work on CentOS CI hosts, and getting Genymotion to work on CentOS seems to require intrusive changes.

Any ideas for a fix or workaround? As a last resort, I could catch the UsbManager NPE, but that would be very bad, since I also use a third-party library that interacts with UsbManager .

+8
android android-emulator usb
source share
1 answer

https://developer.android.com/reference/android/content/Context.html#getSystemService(java.lang.String)

RETURN Object The service or null if the name does not exist.

According to the API, an implementation is not required to return null .

Work: easy.

 UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE); if (usbManager == null) { Log.w("MyApp","USB Not supported"); return; } // Normal route usbManager.getDeviceList(); 

(I also ran into the same problem in the emulator as you described)

0
source share

All Articles