Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Building USB Serial Communication in Android Applications Using Java

Tech 1

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;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.