android 串口demo
时间: 2025-02-04 18:15:42 浏览: 65
### Android 串口通信 示例代码
为了帮助理解如何在Android平台上实现串口通信,下面展示一段简化版的示例代码。这段代码主要集中在创建`SerialPort`对象以及基本的数据发送接收功能。
#### 创建 `SerialPort`
首先,在应用中需要定义一个类来管理串口连接:
```java
import android.util.Log;
public class SerialPort {
private static final String TAG = "SerialPort";
// 构造函数用于初始化串口参数
public SerialPort(File device, int baudrate) throws SecurityException, IOException {
mFileDescriptor = open(device.getAbsolutePath(), baudrate);
if (mFileDescriptor == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFd = mFileDescriptor.getInt$();
File descriptor = new File("/proc/self/fd/" + mFd);
mInputStream = new FileInputStream(descriptor);
mOutputStream = new FileOutputStream(descriptor);
}
// 打开串口并设置波特率和其他属性
private native static Object open(String path, int baudrate);
// 关闭串口的方法
public synchronized void close() {
if (mFileDescriptor != null) {
close(mFd);
mFileDescriptor.close();
mFileDescriptor = null;
}
}
private native static void close(int fd);
// 发送数据到串口
public void send(byte[] buffer) throws IOException {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Error on write", e);
throw e;
}
}
// 接收来自串口的数据
public byte[] receive() throws IOException {
byte[] buffer = new byte[1024];
int len = -1;
try {
while ((len = mInputStream.read(buffer)) > 0) {
return Arrays.copyOfRange(buffer, 0, len);
}
} catch (IOException e) {
Log.e(TAG, "Error on read", e);
throw e;
}
return null;
}
private Object mFileDescriptor; // Native file descriptor.
private int mFd; // File descriptor as returned by the C code.
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
}
```
此部分实现了基础的串口打开、关闭、读取和写入操作[^1]。
#### 数据交换逻辑
当涉及到实际的应用场景时,可能还需要构建更复杂的机制处理接收到的信息或是定时向另一端发送命令。这里给出了一种简单的方案——利用线程持续监听输入流的变化,并将获取的内容传递给主线程更新UI界面;对于输出,则可以直接调用上述提到的send方法完成消息推送。
```java
// 假设有一个Handler实例handler存在于Activity或其他组件内部,
// 它负责把子线程中的事件转发至UI线程。
private Handler handler = new Handler(Looper.getMainLooper());
new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
byte[] data = serialPort.receive(); // 调用之前定义好的receive()
if(data!=null){
Message msg = handler.obtainMessage();
Bundle bundle=new Bundle();
bundle.putByteArray("data",data);
msg.setData(bundle);
handler.sendMessage(msg);
}
} catch (IOException ignored) {}
}
}).start();
// UI线程中处理接收到的消息
@Override
protected void handleMessage(Message message) {
super.handleMessage(message);
byte[] receivedData=message.getData().getByteArray("data");
// 更新UI或者其他业务逻辑...
}
// 当想要发送指令的时候可以在任意地方这样调用:
try{
serialPort.send(command.getBytes());
}catch(IOException ex){
Toast.makeText(context,"Failed to Send Command.",Toast.LENGTH_SHORT).show();
}
```
以上就是关于Android平台下串口通讯的一个简单例子[^4]。
阅读全文
相关推荐
















