├── .gitignore ├── LICENSE ├── MySerialPort ├── .gitignore ├── app │ ├── .gitignore │ ├── build.gradle │ ├── libs │ │ ├── armeabi-v7a │ │ │ └── libserial_port.so │ │ ├── armeabi │ │ │ └── libserial_port.so │ │ └── x86 │ │ │ └── libserial_port.so │ ├── proguard-rules.pro │ └── src │ │ ├── androidTest │ │ └── java │ │ │ └── cn │ │ │ └── humiao │ │ │ └── myserialport │ │ │ └── ExampleInstrumentedTest.java │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ │ ├── android_serialport_api │ │ │ │ ├── SerialPort.java │ │ │ │ └── SerialPortFinder.java │ │ │ └── cn │ │ │ │ └── humiao │ │ │ │ └── myserialport │ │ │ │ ├── Cmd.java │ │ │ │ ├── DataUtils.java │ │ │ │ ├── MainActivity.java │ │ │ │ └── SerialPortUtil.java │ │ └── res │ │ │ ├── layout │ │ │ └── activity_main.xml │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ └── values │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── test │ │ └── java │ │ └── cn │ │ └── humiao │ │ └── myserialport │ │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | MySerialPort/.idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 白如白牙 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MySerialPort/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /MySerialPort/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /MySerialPort/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion "26.0.1" 6 | defaultConfig { 7 | applicationId "cn.humiao.myserialport" 8 | minSdkVersion 14 9 | targetSdkVersion 26 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | sourceSets { 15 | main { 16 | jniLibs.srcDirs = ['libs'] 17 | } 18 | } 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | } 26 | 27 | dependencies { 28 | compile fileTree(dir: 'libs', include: ['*.jar']) 29 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 30 | exclude group: 'com.android.support', module: 'support-annotations' 31 | }) 32 | compile 'com.android.support:appcompat-v7:26.+' 33 | compile 'com.android.support.constraint:constraint-layout:1.0.2' 34 | testCompile 'junit:junit:4.12' 35 | compile 'org.greenrobot:eventbus:3.0.0' 36 | } 37 | -------------------------------------------------------------------------------- /MySerialPort/app/libs/armeabi-v7a/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/libs/armeabi-v7a/libserial_port.so -------------------------------------------------------------------------------- /MySerialPort/app/libs/armeabi/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/libs/armeabi/libserial_port.so -------------------------------------------------------------------------------- /MySerialPort/app/libs/x86/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/libs/x86/libserial_port.so -------------------------------------------------------------------------------- /MySerialPort/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\AndroidSdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /MySerialPort/app/src/androidTest/java/cn/humiao/myserialport/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package cn.humiao.myserialport; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("cn.humiao.myserialport", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/java/android_serialport_api/SerialPort.java: -------------------------------------------------------------------------------- 1 | package android_serialport_api; 2 | 3 | import android.util.Log; 4 | 5 | import java.io.File; 6 | import java.io.FileDescriptor; 7 | import java.io.FileInputStream; 8 | import java.io.FileOutputStream; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.io.OutputStream; 12 | 13 | /** 14 | * Google官方代码 15 | * 此类的作用为,JNI的调用,用来加载.so文件的 16 | * 获取串口输入输出流 17 | */ 18 | 19 | public class SerialPort { 20 | 21 | private static final String TAG = "SerialPort"; 22 | 23 | /* 24 | * Do not remove or rename the field mFd: it is used by native method 25 | * close(); 26 | */ 27 | private FileDescriptor mFd; 28 | private FileInputStream mFileInputStream; 29 | private FileOutputStream mFileOutputStream; 30 | 31 | public SerialPort(File device, int baudrate, int flags) 32 | throws SecurityException, IOException { 33 | 34 | /* Check access permission */ 35 | if (!device.canRead() || !device.canWrite()) { 36 | try { 37 | /* Missing read/write permission, trying to chmod the file */ 38 | Process su; 39 | su = Runtime.getRuntime().exec("/system/bin/su"); 40 | String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" 41 | + "exit\n"; 42 | su.getOutputStream().write(cmd.getBytes()); 43 | if ((su.waitFor() != 0) || !device.canRead() 44 | || !device.canWrite()) { 45 | throw new SecurityException(); 46 | } 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | throw new SecurityException(); 50 | } 51 | } 52 | 53 | System.out.println(device.getAbsolutePath() 54 | + "=============================="); 55 | 56 | mFd = open(device.getAbsolutePath(), baudrate, flags); 57 | if (mFd == null) { 58 | Log.e(TAG, "native open returns null"); 59 | throw new IOException(); 60 | } 61 | mFileInputStream = new FileInputStream(mFd); 62 | mFileOutputStream = new FileOutputStream(mFd); 63 | } 64 | 65 | // Getters and setters 66 | public InputStream getInputStream() { 67 | return mFileInputStream; 68 | } 69 | 70 | public OutputStream getOutputStream() { 71 | return mFileOutputStream; 72 | } 73 | 74 | 75 | // JNI 76 | private native static FileDescriptor open(String path, int baudrate, 77 | int flags); 78 | 79 | public native void close(); 80 | 81 | static { 82 | System.out.println("=============================="); 83 | System.loadLibrary("serial_port"); 84 | System.out.println("********************************"); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/java/android_serialport_api/SerialPortFinder.java: -------------------------------------------------------------------------------- 1 | package android_serialport_api; 2 | 3 | import android.util.Log; 4 | 5 | import java.io.File; 6 | import java.io.FileReader; 7 | import java.io.IOException; 8 | import java.io.LineNumberReader; 9 | import java.util.Iterator; 10 | import java.util.Vector; 11 | 12 | /** 13 | * Google官方代码 14 | * 此类的作用为,寻找得到有效的串口的物理地址。 15 | * 如果你本身就知道串口的地址如:ttyS1、ttyS2,那么这个类就可以不用了。 16 | * 17 | */ 18 | 19 | public class SerialPortFinder { 20 | 21 | public class Driver { 22 | public Driver(String name, String root) { 23 | mDriverName = name; 24 | mDeviceRoot = root; 25 | } 26 | private String mDriverName; 27 | private String mDeviceRoot; 28 | Vector mDevices = null; 29 | public Vector getDevices() { 30 | if (mDevices == null) { 31 | mDevices = new Vector(); 32 | File dev = new File("/dev"); 33 | File[] files = dev.listFiles(); 34 | int i; 35 | for (i=0; i mDrivers = null; 52 | 53 | Vector getDrivers() throws IOException { 54 | if (mDrivers == null) { 55 | mDrivers = new Vector(); 56 | LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers")); 57 | String l; 58 | while((l = r.readLine()) != null) { 59 | // Issue 3: 60 | // Since driver name may contain spaces, we do not extract driver name with split() 61 | String drivername = l.substring(0, 0x15).trim(); 62 | String[] w = l.split(" +"); 63 | if ((w.length >= 5) && (w[w.length-1].equals("serial"))) { 64 | Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length-4]); 65 | mDrivers.add(new Driver(drivername, w[w.length-4])); 66 | } 67 | } 68 | r.close(); 69 | } 70 | return mDrivers; 71 | } 72 | 73 | public String[] getAllDevices() { 74 | Vector devices = new Vector(); 75 | // Parse each driver 76 | Iterator itdriv; 77 | try { 78 | itdriv = getDrivers().iterator(); 79 | while(itdriv.hasNext()) { 80 | Driver driver = itdriv.next(); 81 | Iterator itdev = driver.getDevices().iterator(); 82 | while(itdev.hasNext()) { 83 | String device = itdev.next().getName(); 84 | String value = String.format("%s (%s)", device, driver.getName()); 85 | devices.add(value); 86 | } 87 | } 88 | } catch (IOException e) { 89 | e.printStackTrace(); 90 | } 91 | return devices.toArray(new String[devices.size()]); 92 | } 93 | 94 | public String[] getAllDevicesPath() { 95 | Vector devices = new Vector(); 96 | // Parse each driver 97 | Iterator itdriv; 98 | try { 99 | itdriv = getDrivers().iterator(); 100 | while(itdriv.hasNext()) { 101 | Driver driver = itdriv.next(); 102 | Iterator itdev = driver.getDevices().iterator(); 103 | while(itdev.hasNext()) { 104 | String device = itdev.next().getAbsolutePath(); 105 | devices.add(device); 106 | } 107 | } 108 | } catch (IOException e) { 109 | e.printStackTrace(); 110 | } 111 | return devices.toArray(new String[devices.size()]); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/java/cn/humiao/myserialport/Cmd.java: -------------------------------------------------------------------------------- 1 | package cn.humiao.myserialport; 2 | 3 | /** 4 | * @author by AllenJ on 2018/5/3. 5 | */ 6 | 7 | public interface Cmd { 8 | String OPEN_DOOR = "010100000000FFFF"; 9 | } 10 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/java/cn/humiao/myserialport/DataUtils.java: -------------------------------------------------------------------------------- 1 | package cn.humiao.myserialport; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 串口数据转换工具类 8 | * Created by Administrator on 2016/6/2. 9 | */ 10 | public class DataUtils { 11 | //------------------------------------------------------- 12 | // 判断奇数或偶数,位运算,最后一位是1则为奇数,为0是偶数 13 | public static int isOdd(int num) { 14 | return num & 1; 15 | } 16 | 17 | //------------------------------------------------------- 18 | //Hex字符串转int 19 | public static int HexToInt(String inHex) { 20 | return Integer.parseInt(inHex, 16); 21 | } 22 | 23 | public static String IntToHex(int intHex){ 24 | return Integer.toHexString(intHex); 25 | } 26 | 27 | //------------------------------------------------------- 28 | //Hex字符串转byte 29 | public static byte HexToByte(String inHex) { 30 | return (byte) Integer.parseInt(inHex, 16); 31 | } 32 | 33 | //------------------------------------------------------- 34 | //1字节转2个Hex字符 35 | public static String Byte2Hex(Byte inByte) { 36 | return String.format("%02x", new Object[]{inByte}).toUpperCase(); 37 | } 38 | 39 | //------------------------------------------------------- 40 | //字节数组转转hex字符串 41 | public static String ByteArrToHex(byte[] inBytArr) { 42 | StringBuilder strBuilder = new StringBuilder(); 43 | for (byte valueOf : inBytArr) { 44 | strBuilder.append(Byte2Hex(Byte.valueOf(valueOf))); 45 | strBuilder.append(" "); 46 | } 47 | return strBuilder.toString(); 48 | } 49 | 50 | //------------------------------------------------------- 51 | //字节数组转转hex字符串,可选长度 52 | public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) { 53 | StringBuilder strBuilder = new StringBuilder(); 54 | int j = byteCount; 55 | for (int i = offset; i < j; i++) { 56 | strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i]))); 57 | } 58 | return strBuilder.toString(); 59 | } 60 | 61 | //------------------------------------------------------- 62 | //转hex字符串转字节数组 63 | public static byte[] HexToByteArr(String inHex) { 64 | byte[] result; 65 | int hexlen = inHex.length(); 66 | if (isOdd(hexlen) == 1) { 67 | hexlen++; 68 | result = new byte[(hexlen / 2)]; 69 | inHex = "0" + inHex; 70 | } else { 71 | result = new byte[(hexlen / 2)]; 72 | } 73 | int j = 0; 74 | for (int i = 0; i < hexlen; i += 2) { 75 | result[j] = HexToByte(inHex.substring(i, i + 2)); 76 | j++; 77 | } 78 | return result; 79 | } 80 | 81 | /** 82 | * 按照指定长度切割字符串 83 | * 84 | * @param inputString 需要切割的源字符串 85 | * @param length 指定的长度 86 | * @return 87 | */ 88 | public static List getDivLines(String inputString, int length) { 89 | List divList = new ArrayList<>(); 90 | int remainder = (inputString.length()) % length; 91 | // 一共要分割成几段 92 | int number = (int) Math.floor((inputString.length()) / length); 93 | for (int index = 0; index < number; index++) { 94 | String childStr = inputString.substring(index * length, (index + 1) * length); 95 | divList.add(childStr); 96 | } 97 | if (remainder > 0) { 98 | String cStr = inputString.substring(number * length, inputString.length()); 99 | divList.add(cStr); 100 | } 101 | return divList; 102 | } 103 | 104 | /** 105 | * 计算长度,两个字节长度 106 | * 107 | * @param val value 108 | * @return 结果 109 | */ 110 | public static String twoByte(String val) { 111 | if (val.length() > 4) { 112 | val = val.substring(0, 4); 113 | } else { 114 | int l = 4 - val.length(); 115 | for (int i = 0; i < l; i++) { 116 | val = "0" + val; 117 | } 118 | } 119 | return val; 120 | } 121 | 122 | /** 123 | * 校验和 124 | * 125 | * @param cmd 指令 126 | * @return 结果 127 | */ 128 | public static String sum(String cmd) { 129 | List cmdList = DataUtils.getDivLines(cmd, 2); 130 | int sumInt = 0; 131 | for (String c : cmdList) { 132 | sumInt += DataUtils.HexToInt(c); 133 | } 134 | String sum = DataUtils.IntToHex(sumInt); 135 | sum = DataUtils.twoByte(sum); 136 | cmd += sum; 137 | return cmd.toUpperCase(); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/java/cn/humiao/myserialport/MainActivity.java: -------------------------------------------------------------------------------- 1 | package cn.humiao.myserialport; 2 | 3 | import android.support.v7.app.AppCompatActivity; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.TextView; 9 | 10 | import org.greenrobot.eventbus.EventBus; 11 | import org.greenrobot.eventbus.Subscribe; 12 | import org.greenrobot.eventbus.ThreadMode; 13 | 14 | 15 | public class MainActivity extends AppCompatActivity { 16 | private String TAG = "MainActivity"; 17 | private Button button; 18 | private TextView tv; 19 | private SerialPortUtil serialPortUtil; 20 | 21 | @Override 22 | protected void onCreate(Bundle savedInstanceState) { 23 | super.onCreate(savedInstanceState); 24 | setContentView(R.layout.activity_main); 25 | button = (Button) findViewById(R.id.btn); 26 | tv = (TextView) findViewById(R.id.tv); 27 | serialPortUtil = new SerialPortUtil(); 28 | serialPortUtil.openSerialPort(); 29 | //注册EventBus 30 | EventBus.getDefault().register(this); 31 | button.setOnClickListener(new View.OnClickListener() { 32 | @Override 33 | public void onClick(View v) { 34 | serialPortUtil.sendSerialPort(Cmd.OPEN_DOOR); 35 | } 36 | }); 37 | } 38 | 39 | /** 40 | * 用EventBus进行线程间通信,也可以使用Handler 41 | * @param string 42 | */ 43 | @Subscribe(threadMode = ThreadMode.MAIN) 44 | public void onEventMainThread(String string){ 45 | Log.d(TAG,"获取到了从传感器发送到Android主板的串口数据"); 46 | tv.setText(string); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/java/cn/humiao/myserialport/SerialPortUtil.java: -------------------------------------------------------------------------------- 1 | package cn.humiao.myserialport; 2 | 3 | import android.util.Log; 4 | 5 | import org.greenrobot.eventbus.EventBus; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.OutputStream; 11 | 12 | import android_serialport_api.SerialPort; 13 | 14 | /** 15 | * @author by AllenJ on 2018/4/20. 16 | * 17 | * 通过串口用于接收或发送数据 18 | */ 19 | 20 | public class SerialPortUtil { 21 | 22 | private SerialPort serialPort = null; 23 | private InputStream inputStream = null; 24 | private OutputStream outputStream = null; 25 | private ReceiveThread mReceiveThread = null; 26 | private boolean isStart = false; 27 | 28 | /** 29 | * 打开串口,接收数据 30 | * 通过串口,接收单片机发送来的数据 31 | */ 32 | public void openSerialPort() { 33 | try { 34 | serialPort = new SerialPort(new File("/dev/ttyS0"), 9600, 0); 35 | //调用对象SerialPort方法,获取串口中"读和写"的数据流 36 | inputStream = serialPort.getInputStream(); 37 | outputStream = serialPort.getOutputStream(); 38 | isStart = true; 39 | 40 | } catch (IOException e) { 41 | e.printStackTrace(); 42 | } 43 | getSerialPort(); 44 | } 45 | 46 | /** 47 | * 关闭串口 48 | * 关闭串口中的输入输出流 49 | */ 50 | public void closeSerialPort() { 51 | Log.i("test", "关闭串口"); 52 | try { 53 | if (inputStream != null) { 54 | inputStream.close(); 55 | } 56 | if (outputStream != null) { 57 | outputStream.close(); 58 | } 59 | isStart = false; 60 | } catch (IOException e) { 61 | e.printStackTrace(); 62 | } 63 | 64 | } 65 | 66 | /** 67 | * 发送数据 68 | * 通过串口,发送数据到单片机 69 | * 70 | * @param data 要发送的数据 71 | */ 72 | public void sendSerialPort(String data) { 73 | try { 74 | byte[] sendData = DataUtils.HexToByteArr(data); 75 | outputStream.write(sendData); 76 | outputStream.flush(); 77 | } catch (IOException e) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | 82 | private void getSerialPort() { 83 | if (mReceiveThread == null) { 84 | 85 | mReceiveThread = new ReceiveThread(); 86 | } 87 | mReceiveThread.start(); 88 | } 89 | 90 | /** 91 | * 接收串口数据的线程 92 | */ 93 | 94 | private class ReceiveThread extends Thread { 95 | @Override 96 | public void run() { 97 | super.run(); 98 | //条件判断,只要条件为true,则一直执行这个线程 99 | while (isStart) { 100 | if (inputStream == null) { 101 | return; 102 | } 103 | byte[] readData = new byte[1024]; 104 | try { 105 | int size = inputStream.read(readData); 106 | if (size > 0) { 107 | String readString = DataUtils.ByteArrToHex(readData, 0, size); 108 | EventBus.getDefault().post(readString); 109 | } 110 | 111 | } catch (IOException e) { 112 | e.printStackTrace(); 113 | } 114 | } 115 | 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /MySerialPort/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 |