一、app目录下添加
implementation 'io.github.xmaihh:serialport:2.1.1'
1) 点击Sync Now更新依赖
2) AndroidManifest.xml文件添加读取设备信息权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
二、 使用
1) 创建MySerialPort.java文件
package com.youlian.weight.serialport;import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;import java.io.IOException;
import java.util.Arrays;import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.utils.ByteUtil;public class MySerialPort {private SerialHelper serialHelper = null;private String Tag = "MySerialPort";private Handler handler;private boolean isHexType = true;private Context context;public MySerialPort(String port, Context context){this.context = context;serialHelper = new SerialHelper(port, 9600) {@Overrideprotected void onDataReceived(ComBean paramComBean) {
// String time = paramComBean.sRecTime;String rxText = new String(paramComBean.bRec);if (isHexType) {//转成十六进制数据rxText = ByteUtil.ByteArrToHex(paramComBean.bRec);}
// Log.d(Tag,"收到消息:"+rxText);handler = new Handler(Looper.getMainLooper());String finalRxText = rxText;handler.post(new Runnable() {@Overridepublic void run() {typeOperate(finalRxText);}});}};serialHelper.setStopBits(1); //设置停止位serialHelper.setDataBits(8); //设置数据位serialHelper.setParity(0); //设置校验位serialHelper.setFlowCon(0); //设置流控try {serialHelper.open();}catch (IOException e){Log.e(Tag,"串口打开失败");}}/*** 返回指令判断* @param data*/private void typeOperate(String data){Log.d(Tag,"返回数据:" + data);}/*** 发送byte[]* @param bOutArray*/public void sendByte(byte[] bOutArray){Log.e(Tag,"发送byte[]:"+ Arrays.toString(bOutArray));serialHelper.send(bOutArray);}/*** 发送Hex* @param sHex*/public void sendHex(String sHex) {// Log.e(Tag, "发送Hex:" + sHex + ", 时间:" + getTime());serialHelper.sendHex(sHex);}/*** 发送ASCII* @param sTxt*/public void sendTxt(String sTxt){Log.e(Tag,"发送ASCII:"+sTxt);serialHelper.sendTxt(sTxt);}/*** 打开串口*/public void open(){try {serialHelper.open();}catch (Exception e){Log.e(Tag,"串口打开失败");}}/*** 关闭串口*/public void close(){serialHelper.close();}
}
2) 实例化
import com.you.weight.serialport.MySerialPort;public static MySerialPort mySerialPort = null;// /dev/ttyS3是你自己插的串口名称
mySerialPort = new MySerialPort("/dev/ttyS3", MainActivity.this);