要在Android設備上通過串口發送數據,可以使用Java中的SerialPort類來實現。以下是一個簡單的示例代碼,演示如何在Android設備上通過串口發送數據:
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
public class SerialPortSender {
private UsbDeviceConnection connection;
private OutputStream outputStream;
public SerialPortSender(UsbDeviceConnection connection) {
this.connection = connection;
this.outputStream = connection.openOutputStream();
}
public void sendData(byte[] data) {
try {
outputStream.write(data);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static UsbDeviceConnection findSerialPortConnection(UsbManager usbManager) {
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
UsbDeviceConnection connection = null;
for (UsbDevice device : deviceList.values()) {
if (device.getVendorId() == VENDOR_ID && device.getProductId() == PRODUCT_ID) {
connection = usbManager.openDevice(device);
break;
}
}
return connection;
}
}
在上面的代碼中,SerialPortSender
類負責實現與串口的連接和數據發送功能。sendData
方法用于發送數據,findSerialPortConnection
方法用于查找串口連接。要使用該類,可以在Android應用的主活動中進行調用:
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbDeviceConnection connection = SerialPortSender.findSerialPortConnection(usbManager);
if (connection != null) {
SerialPortSender sender = new SerialPortSender(connection);
byte[] data = "Hello, world!".getBytes();
sender.sendData(data);
} else {
Log.e(TAG, "Cannot find serial port connection");
}
在上面的代碼中,首先通過UsbManager
獲取USB設備管理器實例,然后通過findSerialPortConnection
方法查找串口連接。如果找到了串口連接,就可以實例化SerialPortSender
類,并通過sendData
方法發送數據。