How to communicate with a USB device?
That string is just a marker so you recognize the intent that is returned when you call registerReceiver(mUsbReceiver, filter);
. That isn't the problem.
I think the problem is here:
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
This line is supposed to get you your USB Manager, but as far as I recall not all phones have to support the Android USB Accessory API. This line is probably just assigning null
to mUsbManager
which then causes you NullPointerException
when you call a method on it further down in the code. Trying checking if that isn't null
before making a call on it.
For more info, checkout these links:
- http://developer.android.com/guide/topics/usb/index.html
- http://developer.android.com/guide/topics/usb/accessory.html
EDIT:
I think I see what the issue is now. You're right, it's not the USB Manager. It's the UsbDevice object (device
). It is never initialized anywhere in your code. In this line :
mUsbManager.requestPermission(device, mPermissionIntent);
you're basically firing off an intent to ask the user if it's okay for you to work with the device represented by the UsbDevice object device
. However when this call gets fired device
has not yet been initialized (and therefore has the default value of null
). So when you try to request permission you end up getting a NullPointerException
instead of the expected result. To fix this you need to figure out which device you want to connect to and assign it to device
. Look in here, under "Enumerating devices" to figure out different ways to do that. One way, if you know the name of the device you want to connect to, is to make the following calls after you retrieve the Usb Manager:
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
device = deviceList.get("<deviceName>");
(Obviously, you would replace <deviceName>
with the actual name of the device.
minSdkVersion
must >= 12
To enable USB host API support you should add a file named android.hardware.usb.host.xml and containing the following lines:
<permissions>
<feature name="android.hardware.usb.host"/>