android中串口serialport接收数据demo
时间: 2023-10-18 21:02:45 浏览: 62
Android中串口(SerialPort)接收数据的Demo示例如下:
```java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android_serialport_api.SerialPort;
public class SerialPortActivity extends AppCompatActivity {
private SerialPort mSerialPort;
private InputStream mInputStream;
private ReadThread mReadThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_serial_port);
try {
mSerialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);
mInputStream = mSerialPort.getInputStream();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mReadThread = new ReadThread();
mReadThread.start();
}
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
while (!isInterrupted()) {
try {
if (mInputStream == null) {
return;
}
byte[] buffer = new byte[1024];
int size = mInputStream.read(buffer);
if (size > 0) {
String data = new String(buffer, 0, size);
Log.d("SerialPort", "Received data: " + data);
// 处理接收到的数据...
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReadThread != null) {
mReadThread.interrupt();
mReadThread = null;
}
if (mSerialPort != null) {
mSerialPort.close();
mSerialPort = null;
}
}
}
```
以上是一个Android中通过串口接收数据的示例代码。在`onCreate`方法中,首先打开串口并获取输入流。然后创建一个`ReadThread`线程用于循环读取串口数据。在`ReadThread`线程的`run`方法中通过`InputStream`的`read`方法读取数据,并将读取到的数据进行处理(这里只是简单地打印出来)。在`onDestroy`方法中,关闭串口和销毁线程。
需要注意的是,这里使用到了一个`android_serialport_api`库,需要在项目的`build.gradle`文件中添加对应的依赖。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)