├── .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 |
13 |
14 |
21 |
22 |
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | MySerialPort
3 |
4 |
--------------------------------------------------------------------------------
/MySerialPort/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/MySerialPort/app/src/test/java/cn/humiao/myserialport/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package cn.humiao.myserialport;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/MySerialPort/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/MySerialPort/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/MySerialPort/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jzt-Tesla/GoogleSerialPort/f75331c09d21eba4a0b9e5af23a46c4c8a2c5379/MySerialPort/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/MySerialPort/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu May 03 19:12:00 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/MySerialPort/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/MySerialPort/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/MySerialPort/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 说明
2 |
3 | 1. 学会如何使用JNI的调用
4 | 2. 知道如何利用串口接收和发送数据
5 | 3. 了解Google的设计思维
6 |
7 |
--------------------------------------------------------------------------------