我有一些代码,看起来像
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
usbManager.getDeviceList();当我使用Android 5.0模拟器时,我得到了这个崩溃:
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)
...我知道官方的Android模拟器不支持USB,但我希望看到一个空的USB设备列表,而不是崩溃。
我在安卓代码中写了点东西,ServiceManager的服务地图上没有"usb"的条目,安卓21栈中似乎没有任何东西能处理ServiceManager返回的空值。
该代码在模拟的4.4设备上运行良好,但在5.0设备上崩溃。CPU架构似乎没有什么不同;我尝试过ARM和x86。
它在我尝试过的所有Genymotion设备上也运行得很好,但我需要让它在CentOS CI主机上运行,而让Genymotion在CentOS上运行似乎需要进行侵入性的更改。
对于修复或解决方法有什么想法吗?作为最后的手段,我可以捕获UsbManager的NPE,但这将是相当糟糕的,因为我还使用了一个与UsbManager交互的第三方库。
发布于 2017-04-05 02:25:15
返回Object The service or null if the name does not exist.
根据API,实现不一定要返回非null值。
变通方法:简单。
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
if (usbManager == null) {
Log.w("MyApp","USB Not supported");
return;
}
// Normal route
usbManager.getDeviceList();(我在Emulator上也遇到过您所描述的相同问题)
https://stackoverflow.com/questions/29023753
复制相似问题