diff --git a/serial/build.gradle b/serial/build.gradle index becdf40..46b7f05 100644 --- a/serial/build.gradle +++ b/serial/build.gradle @@ -8,8 +8,8 @@ android { defaultConfig { minSdkVersion 15 targetSdkVersion 28 - versionCode 9 - versionName "1.2.5" + versionCode 10 + versionName "1.2.6" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles 'consumer-rules.pro' diff --git a/serial/src/main/java/org/sheedon/serial/serialport/SafeThread.java b/serial/src/main/java/org/sheedon/serial/serialport/SafeThread.java index 0431c89..732f9e0 100644 --- a/serial/src/main/java/org/sheedon/serial/serialport/SafeThread.java +++ b/serial/src/main/java/org/sheedon/serial/serialport/SafeThread.java @@ -77,6 +77,24 @@ protected void execute() { } }; + public void close() { + if (pingTimer != null) { + pingTimer.cancel(); + pingTimer = null; + } + + if (pingTask != null) { + pingTask.cancel(); + pingTask = null; + } + + if (thread != null) { + thread.interrupt(); + thread = null; + } + + } + interface OnThreadHandleListener { void readThread(); } diff --git a/serial/src/main/java/org/sheedon/serial/serialport/SerialPort.java b/serial/src/main/java/org/sheedon/serial/serialport/SerialPort.java index dcbff91..42cec38 100644 --- a/serial/src/main/java/org/sheedon/serial/serialport/SerialPort.java +++ b/serial/src/main/java/org/sheedon/serial/serialport/SerialPort.java @@ -19,7 +19,7 @@ * @Email: sheedonsun@163.com * @Date: 2020/2/21 9:27 */ -public class SerialPort implements SafeThread.OnThreadHandleListener{ +public class SerialPort implements SafeThread.OnThreadHandleListener { private android.serialport.SerialPort serialPort; private InputStream inputStream; @@ -58,7 +58,7 @@ public SerialPort(String path, int baudRate, int flags, int interval, outputStream = serialPort.getOutputStream(); safeThread = new SafeThread(); - safeThread.initConfig(interval,this); + safeThread.initConfig(interval, this); } @@ -113,7 +113,8 @@ private void dealWithData() { * @throws NullPointerException 如果inputStream为空,就抛出异常 */ private synchronized byte[] getDataByte() throws NullPointerException { - if (inputStream == null) throw new NullPointerException("is null"); + if (inputStream == null) + return null; try { int size = inputStream.available(); if (size > 0) { @@ -140,7 +141,8 @@ public boolean sendMessage(String data) { * @param bytes 显示的16进制的字符串 */ private boolean setData(byte[] bytes) throws NullPointerException { - if (outputStream == null) throw new NullPointerException("outputStream为空"); + if (outputStream == null) + return false; try { outputStream.write(bytes); return true;//发送成功 @@ -154,6 +156,10 @@ private boolean setData(byte[] bytes) throws NullPointerException { * 关闭串口 */ public void closeSerialPort() { + if(safeThread != null){ + safeThread.close(); + safeThread = null; + } if (serialPort != null) { serialPort.close(); serialPort = null;