I have some code which looks like
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
usbManager.getDeviceList();
When I use an 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 has no USB support, but I would expect to see an empty list of USB devices rather than a crash.
I peaked in the Android code a bit, and ServiceManager
's map of services didn't have an entry for "usb"
. Nothing in the Android 21 stack seems to handle the null value returned by ServiceManager
.
The code works fine on emulated 4.4 devices, but crashes on 5.0 devices. CPU architecture doesn't seem to make a difference; I tried ARM and x86.
It also works fine on all Genymotion devices I've tried, but I need to get this working on CentOS CI hosts, and getting Genymotion to run on CentOS seems to require intrusive changes.
Any ideas for a fix or workaround? As a last resort I could catch UsbManager
's NPE, but it would be pretty bad as I also use a third party library which interacts with UsbManager
.
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.
As per API, implementation is not obliged to returned a non null
value.
Work around: simple.
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
if (usbManager == null) {
Log.w("MyApp","USB Not supported");
return;
}
// Normal route
usbManager.getDeviceList();
(I have also faced the same issue on Emulator as you described)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With