Building USB Serial Communication in Android Applications Using Java
Core Implementation Steps
| Step Number | Core Action |
|---|---|
| 1 | Add Serial Communication Libray Dependency |
| 2 | Initialize Serial Port Objects and Device Connection |
| 3 | Configure and Open the Serial Port |
| 4 | Implement Data Reading Mechanism |
| 5 | Implement Data Writing Mechanism |
| 6 | Safely Close the Serial Port |
1. Adding Serial Communication Library Dependency
Include the widely used USB serial library in your project's module-level build.gradle file:
dependencies {
implementation 'com.felhr:usb-serial-for-android:3.3.0'
}
2. Initializing Serial Port and Device Connection
In the Activity or Fragment where serial communication will occur, declare necessary variables:
// Serial communication core objects
private UsbSerialDevice mSerialPort;
private UsbDevice mTargetDevice;
private UsbManager mUsbManager;
private UsbDeviceConnection mUsbConnection;
3. Opening the Serial Port
First, obtain the USB manager system service and enumerate available USB serial devices to find the target one. Then, open the connection and initialize the serial port instance with standard parameters (e.g., 9600 baud rate, 8 data bits, 1 stop bit, no parity):
// Get USB manager
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// Enumerate connected USB devices to find mTargetDevice
HashMap<String, UsbDevice> connectedDevices = mUsbManager.getDeviceList();
for (Map.Entry<String, UsbDevice> entry : connectedDevices.entrySet()) {
UsbDevice device = entry.getValue();
// Filter target device by vendor/product ID or other identifiers
if (device.getVendorId() == 0x1A86 && device.getProductId() == 0x7523) {
mTargetDevice = device;
break;
}
}
// Check if device is found and open connection
if (mTargetDevice != null) {
mUsbConnection = mUsbManager.openDevice(mTargetDevice);
if (mUsbConnection != null) {
mSerialPort = UsbSerialDevice.createUsbSerialDevice(mTargetDevice, mUsbConnection);
if (mSerialPort != null && !mSerialPort.isOpen()) {
mSerialPort.open();
// Configure common serial parameters
try {
mSerialPort.setBaudRate(9600);
mSerialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
mSerialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
mSerialPort.setParity(UsbSerialInterface.PARITY_NONE);
mSerialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
4. Reading Data from Serial Port
Set up a read callback to listen for incoming serial data automatically:
// Data read callback implementation
private UsbSerialInterface.UsbReadCallback mReadCallback = new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] bytes) {
// Convert raw bytes to readable string (adjust encoding based on device protocol)
String receivedData = new String(bytes, StandardCharsets.UTF_8);
// Handle received data (e.g., update UI, parse protocol)
runOnUiThread(() -> {
Log.d("SerialComm", "Received: " + receivedData.trim());
// Example: display in TextView
mDataDisplayTv.setText(receivedData);
});
}
};
// Start listening for data
if (mSerialPort != null) {
mSerialPort.read(mReadCallback);
}
5. Writing Data to Serial Port
Implement a method to send data as raw bytes over the serial port:
/**
* Sends data over the open serial port
* @param dataToSend String data to be converted and transmitted
*/
private void sendSerialData(String dataToSend) {
if (mSerialPort != null && mSerialPort.isOpen()) {
byte[] rawData = dataToSend.getBytes(StandardCharsets.UTF_8);
mSerialPort.write(rawData);
Log.d("SerialComm", "Sent: " + dataToSend);
} else {
Log.e("SerialComm", "Failed to send: Serial port not open");
}
}
6. Closing the Serial Port
Always close the serial port and connection when communication is no longer needed (e.g., in onPause() or onDestroy()) to avoid resource leaks:
@Override
protected void onDestroy() {
super.onDestroy();
if (mSerialPort != null && mSerialPort.isOpen()) {
mSerialPort.close();
mSerialPort = null;
}
if (mUsbConnection != null) {
mUsbConnection.close();
mUsbConnection = null;
}
mTargetDevice = null;
mUsbManager = null;
}