最近项目需要android和硬件进行通信,通讯方式都是通过串口,android串口通讯google有个开源的demo ,我和很多人一样我也是通过下载这个demo进行开发和研究的。
google android串口通讯开源demo地址: https://github.com/cepr/android-serialport-api
废话也不多说了
1、先把下载的api中这些文件拷进项目的相应位置 ,黑色涂掉的是我项目需要的,
SerialPort类是咱们Android可以调用的类,
SerialPortFinder类是读取设备上面的串口的,面前我是没用上
jni目录下放着c源码和h头文件,
jniLibs下面放的就是so库。
注意:因为用的谷歌原生so库,所以SerialPort类和SerialPortFinder类的包名一定要是android_serialport_api,如果想修改这个包名,就需要重新生成对应的so库,
我理解的是这里放在那个目录下是绝对路径
2、在build.gradle中添加如下代码:
sourceSets {
main {
jniLibs.srcDirs = ['src/main/jniLibs']
jni.srcDirs = []
}
}
3、这样就可以串口通信了
这是串口操作类:
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android_serialport_api.SerialPort;
public class SerialPortUtils {
private final String TAG = "SerialPortUtils";
private String path = "/dev/ttyS3";//修改成你用的
private int baudrate = 9600;//波特率 你用的
public boolean serialPortStatus = false; //是否打开串口标志
public String data_;
public boolean threadStatus =false; //线程状态,为了安全终止线程
public static SerialPort serialPort = null;
public static SerialPortUtils serialPortUtils;
public InputStream inputStream = null;
public OutputStream outputStream = null;
private byte[] outBuf;
private String substring;
/**
* 打开串口
*
* @return serialPort串口对象
*/
public void openSerialPort() {
try {
serialPort = new SerialPort(new File(path), baudrate, 0);
this.serialPortStatus = true;
threadStatus = false; //线程状态
//获取打开的串口中的输入输出流,以便于串口数据的收发
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
ReadThread readThread = new ReadThread();//开始线程监控是否有数据要接收
readThread.start();
} catch (IOException e) {
Log.e("tag", "openSerialPort: 打开串口异常:" + e.toString());
}
Log.d("tag", "openSerialPort: 打开串口");
}
/**
* 关闭串口
*/
public void closeSerialPort() {
try {
this.serialPortStatus = false;
this.threadStatus = true; //线程状态
if (inputStream != null && outputStream != null) {
inputStream.close();
outputStream.close();
}
if (serialPort != null) {
serialPort.close();
serialPort = null;
}
} catch (IOException e) {
Log.e("tag", "closeSerialPort: 关闭串口异常:" + e.toString());
}
Log.d("tag", "closeSerialPort: 关闭串口成功");
}
/**
* 发送串口指令(字符串)
*
* @param data String数据指令
*/
public void sendSerialPort(String data) {
Log.d(TAG, "sendSerialPort: 发送数据");
try {
byte[] sendData = data.getBytes(); //string转byte[]
this.data_ = new String(sendData); //byte[]转string
if (sendData.length > 0) {
outputStream.write(sendData);
outputStream.write('\n');
//outputStream.write('\r'+'\n');
outputStream.flush();
Log.d("tag", "sendSerialPort: 串口数据发送成功");
}
} catch (IOException e) {
Log.e("tag", "sendSerialPort: 串口数据发送失败:" + e.toString());
}
}
/**
* 单开一线程,来读数据
*/
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
while (!threadStatus) {
int size;
try {
if (inputStream == null)
return;
byte[] buffer = new byte[256];
size = inputStream.read(buffer);
if (size > 0) {
if (null != onDataReceiveListener) {
onDataReceiveListener.onDataReceive(buffer, size);
}
}
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
//这是写了一监听器来监听接收数据
public OnDataReceiveListener onDataReceiveListener = null;
public interface OnDataReceiveListener {
void onDataReceive(byte[] buffer, int size);
}
public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
onDataReceiveListener = dataReceiveListener;
}
}
4、activity中只贴一部分代码以及串口数据监听事件
//在onCreate
SerialPortUtils portUtils = new SerialPortUtils();
mOpen = (Button) findViewById(R.id.open);
mClose = (Button) findViewById(R.id.close);
mOpen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
portUtils.openSerialPort();
}
});
mClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
portUtils.closeSerialPort();
mText.setText("");
}
});
mText = (TextView) findViewById(R.id.text);
mText.setText("");
//接收数据的
portUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {
@Override
public void onDataReceive(byte[] buffer, int size) {
sendMessage(500, MyFunc.ByteArrToHex(buffer));
}
});
//Handler 部分
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 100:
mText.setText(msg.obj.toString());
break;
}
}
};
//MyFunc 类里面字节数组转转hex字符串
public static String ByteArrToHex(byte[] inBytArr)
{
StringBuilder strBuilder=new StringBuilder();
int j=inBytArr.length;
for (int i = 0; i < j; i++)
{
strBuilder.append(Byte2Hex(inBytArr[i]));
strBuilder.append(" ");
}
return strBuilder.toString();
}
还有就是SerialPort类里面的报错不用管
就这些了 希望对大家有帮助
资源下载 本来是想设置不要积分的,但是CSDN太恶心了默认设置了积分:点击下载