|
@@ -11,6 +11,7 @@ import java.io.FileInputStream;
|
|
|
import java.io.FileNotFoundException;
|
|
|
import java.io.FileOutputStream;
|
|
|
import java.io.IOException;
|
|
|
+import java.io.Serializable;
|
|
|
import java.util.Timer;
|
|
|
import java.util.TimerTask;
|
|
|
|
|
@@ -26,9 +27,9 @@ import cn.minbb.serialport.listener.OnSerialPortDataListener;
|
|
|
import cn.minbb.serialport.thread.SerialPortReadThread;
|
|
|
|
|
|
/**
|
|
|
- * SerialPortManager
|
|
|
+ * 串口管理器 - 单例模式 防止 反射 克隆 序列化 破坏
|
|
|
*/
|
|
|
-public class SerialPortManager extends SerialPort {
|
|
|
+public class SerialPortManager extends SerialPort implements Serializable, Cloneable {
|
|
|
|
|
|
private static final String TAG = SerialPortManager.class.getSimpleName();
|
|
|
private FileInputStream mFileInputStream;
|
|
@@ -42,6 +43,32 @@ public class SerialPortManager extends SerialPort {
|
|
|
private Handler mSendingHandler;
|
|
|
private SerialPortReadThread mSerialPortReadThread;
|
|
|
|
|
|
+ // 默认是第一次创建
|
|
|
+ private static volatile boolean isCreate = false;
|
|
|
+ // 单例对象
|
|
|
+ private static SerialPortManager serialPortManager = null;
|
|
|
+
|
|
|
+ private SerialPortManager() {
|
|
|
+ if (isCreate) {
|
|
|
+ throw new RuntimeException("已然被实例化一次,不能在实例化");
|
|
|
+ }
|
|
|
+ isCreate = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 线程安全 双重检查加锁
|
|
|
+ */
|
|
|
+ public static SerialPortManager getInstance() {
|
|
|
+ if (null == serialPortManager) {
|
|
|
+ synchronized (SerialPortManager.class) {
|
|
|
+ if (null == serialPortManager) {
|
|
|
+ serialPortManager = new SerialPortManager();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return serialPortManager;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 打开串口
|
|
|
* <p>
|
|
@@ -318,4 +345,16 @@ public class SerialPortManager extends SerialPort {
|
|
|
}
|
|
|
throw new RuntimeException("数据流为空");
|
|
|
}
|
|
|
+
|
|
|
+ @Override
|
|
|
+ protected Object clone() throws CloneNotSupportedException {
|
|
|
+ return serialPortManager;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 防止序列化破坏
|
|
|
+ */
|
|
|
+ private Object readResolve() {
|
|
|
+ return serialPortManager;
|
|
|
+ }
|
|
|
}
|