公司的项目是要做一个应用于工厂的一个物理网系统,android方面需要应用到串口通讯 .通过上网查询到Google官方api,当时为了快速,把这个demo 依赖了
在application里面生成了getSerialPort() 函数,用来获取到SerialPort 对象 都是调用api中的 .so 文件中open函数。public SerialPort getSerialPort(String deviceName) throws SecurityException, IOException, InvalidParameterException { if (mSerialPort == null) { String packageName = getPackageName(); SharedPreferences sp = getSharedPreferences(packageName + "_preferences", MODE_PRIVATE); // int baudRate = Integer.decode(sp.getString("BAUDRATE", "-1")); int baudRate = 9600; if ((deviceName.length() == 0) || (baudRate == -1)) { throw new InvalidParameterException(); } mSerialPort = new SerialPort(new File(deviceName), baudRate, 0); } return mSerialPort; } public void closeSerialPort() { if (mSerialPort != null) { mSerialPort.close(); mSerialPort = null; } }
然后可以写一个专门用于串口通讯的基类。public abstract class SerialPortActivity extends AppCompatActivity { String TAG = "===== 串口通讯Activity界面 ="; protected MyApp mApplication; protected SerialPort mSerialPort; protected OutputStream mOutputStream; private InputStream mInputStream; private ReadThread mReadThread; String deviceName = "/dev/ttyS1"; private class ReadThread extends Thread { @Override public void run() { super.run(); while (!isInterrupted()) { int size; try { byte[] buffer = new byte[1024]; if (mInputStream == null) { return; } size = mInputStream.read(buffer); if (size > 0) { onDataReceived(buffer, size); } } catch (IOException e) { e.printStackTrace(); return; } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApplication = (MyApp) getApplication(); try { mSerialPort = mApplication.getSerialPort(deviceName); mOutputStream = mSerialPort.getOutputStream(); mInputStream = mSerialPort.getInputStream(); /* Create a receiving thread */ mReadThread = new ReadThread(); mReadThread.start(); } catch (SecurityException e) { Toast.makeText(mApplication, "您没有串口的读写权限", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mApplication, "您没有串口的读写权限", Toast.LENGTH_SHORT).show(); } catch (InvalidParameterException e) { Toast.makeText(mApplication, "请先配置串口参数", Toast.LENGTH_SHORT).show(); } Log.e(TAG, " 获取输入流 = " + mInputStream); Log.e(TAG, " 获取输出流 = " + mOutputStream); } protected abstract void onDataReceived(final byte[] buffer, final int size); @Override protected void onDestroy() { if (mReadThread != null) mReadThread.interrupt(); mApplication.closeSerialPort(); mSerialPort = null; super.onDestroy(); } }
通过log 打印出来的只要执行到了open()函数,并且输入输出流不为空 ,那串口通讯就基本完成,剩下的就是和单片机或者
串口模拟助手之间数据的交换了.