I made a similar post about how I can best send data to and receive data from a USB device connected to Android using the native API. Someone turned me toward a library for serial communication, so I'm trying to understand how to use that.
I'm only using some of the example code so far just to see something working, but I'm stuck on trying to open the USB device. Here's a verbose print out of the USB device I'm using. It's a CDC device that should echo back what is sent to it.
Here's that code I have running right now. The app has a single button that does this function.
private void DoTheThing () {
String textMessage = "";
// Find all available drivers from attached devices.
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
textMessage += "Could not find any avaliable drivers.\n";
m_textView.setText(textMessage);
return;
}
// Open a connection to the first available driver.
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
// add UsbManager.requestPermission(driver.getDevice(), ..) handling here
textMessage += "Could not open device.\n";
m_textView.setText(textMessage);
return;
}
UsbSerialPort port = driver.getPorts().get(0); // Most devices have just one port (port 0)
try {
port.open(connection);
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
} catch (IOException e) {
textMessage += e + "\n";
m_textView.setText(textMessage);
return;
}
textMessage += "I did the thing.\n";
m_textView.setText(textMessage);
}
The function stops at the first return where an available driver can not be found. I was having a similar issue before where the native API was failing at opening the device. This library is failing to find an available driver.
I'm testing on a Pixel 3. Could the Pixel it self be lock down the device before I can run my app? I plug the Pixel into my desktop and then 'run app' from Android Studio (I have USB Debugging on and dev options enabled). Once the app is running, then I unplug it from the desktop and plug in my USB device. Could this be altering the state in a weird way?
EDIT:
Got it working with adding permissions.
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
manager.requestPermission(driver.getDevice(), usbPermissionIntent);