溫馨提示×

Android串口如何發(fā)送數(shù)據(jù)

小樊
100
2024-08-03 04:44:14
欄目: 編程語言

要在Android設(shè)備上通過串口發(fā)送數(shù)據(jù),可以使用Java中的SerialPort類來實(shí)現(xiàn)。以下是一個(gè)簡單的示例代碼,演示如何在Android設(shè)備上通過串口發(fā)送數(shù)據(jù):

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類負(fù)責(zé)實(shí)現(xiàn)與串口的連接和數(shù)據(jù)發(fā)送功能。sendData方法用于發(fā)送數(shù)據(jù),findSerialPortConnection方法用于查找串口連接。要使用該類,可以在Android應(yīng)用的主活動(dòng)中進(jìn)行調(diào)用:

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設(shè)備管理器實(shí)例,然后通過findSerialPortConnection方法查找串口連接。如果找到了串口連接,就可以實(shí)例化SerialPortSender類,并通過sendData方法發(fā)送數(shù)據(jù)。

0