一、导入jar包
二、新建三个类
public class SerialPort } catch (Exception e) }mFd = open(device.getAbsolutePath(), baudrate, flags);if (mFd == null) mFileInputStream = new FileInputStream(mFd);mFileOutputStream = new FileOutputStream(mFd);}// Getters and setterspublic InputStream getInputStream() public OutputStream getOutputStream() // JNIprivate native static FileDescriptor open(String path, int baudrate, int flags);public native void close();static }
public class SerialPortFinder private String mDriverName;private String mDeviceRoot;Vector mDevices = null;public Vector getDevices() }}return mDevices;}public String getName() }private static final String TAG = "SerialPort";private Vector mDrivers = null;Vector getDrivers() throws IOException }r.close();}return mDrivers;}public String[] getAllDevices() }} catch (IOException e) return devices.toArray(new String[devices.size()]);}public String[] getAllDevicesPath() }} catch (IOException e) return devices.toArray(new String[devices.size()]);}}
public class SerialPortUtils /** * 打开串口 * @return serialPort串口对象 */public SerialPort openSerialPort(){// path = activity.getUserCustom().getSerialPort();// baudrate = activity.getUserCustom().getBaudRate();Log.e("TAG","选择的串口地址"+path+"波特率:"+baudrate);try catch (IOException e) Log.d(TAG, "openSerialPort: 打开串口");return serialPort;}/** * 关闭串口 */public void closeSerialPort() catch (IOException e) Log.d(TAG, "closeSerialPort: 关闭串口成功");}/** * 发送串口指令(字符串) * @param data String数据指令 */public void sendSerialPort(String data)*/} catch (IOException e) }}/** * 单开一线程,来读数据 */private class ReadThread extends Thread{@Overridepublic void run() } catch (IOException e) }}}//这是写了一监听器来监听接收数据public OnDataReceiveListener onDataReceiveListener = null;public static interface OnDataReceiveListener public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) //byte数组转换成十六进制public String bytesToHexString(byte[] bArr) return sb.toString();}//字符串转byte数组public static byte[] HexToByteArr(String inHex) else int j = 0;for(int i = 0; i < hexlen; i += 2) return result;}public static byte HexToByte(String inHex) }
三、调用
faceActivity.serialPortUtils.openSerialPort();//打开串口faceActivity.serialPortUtils.sendSerialPort(unlockChoice);//发送串口指令"55AA5A01BA01"//串口数据监听事件faceActivity.serialPortUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {@Overridepublic void onDataReceive(byte[] buffer, int size) {//返回指令Log.d("TAG", "进入数据监听事件中。。。" + new String(buffer));////在线程中直接操作UI会报异常:ViewRootImpl$CalledFromWrongThreadException//解决方法:handler///* mBuffer = buffer; handler.post(runnable);*/Log.e("TAG", "size:" + String.valueOf(buffer.length) + "数据监听:" + faceActivity.serialPortUtils.bytesToHexString(buffer));// new String(buffer)}
领取专属 10元无门槛券
私享最新 技术干货