经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Android实现串口通信
来源:jb51  时间:2022/8/15 16:59:20  对本文有异议

本文实例为大家分享了Android实现串口通信的具体代码,供大家参考,具体内容如下

生成so文件

首先确保已经安装了NDK和CMake

然后创建一个SerialPort.java文件

主要用来处理so文件

注意包名一旦写好不要更改位置,具体代码:

  1. import android.util.Log;
  2.  
  3. import java.io.File;
  4. import java.io.FileDescriptor;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. /**
  11. ?* Created by abc on 2021/1/23.
  12. ?*/
  13.  
  14. public class SerialPort {
  15.  
  16.  
  17. ? ? private static final String TAG = "SerialPort";
  18.  
  19. ? ? /*
  20. ? ? ?* Do not remove or rename the field mFd: it is used by native method close();
  21. ? ? ?*/
  22. ? ? private FileDescriptor mFd;
  23. ? ? private FileInputStream mFileInputStream;
  24. ? ? private FileOutputStream mFileOutputStream;
  25.  
  26. ? ? public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
  27.  
  28. ? ? ? ? if (device == null) {
  29. ? ? ? ? ? ? System.out.println("device is null");
  30. ? ? ? ? ? ? return;
  31. ? ? ? ? }
  32.  
  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 777 " + device.getAbsolutePath() + "\n" + "exit\n";
  41. ? ? ? ? ? ? ? ? su.getOutputStream().write(cmd.getBytes());
  42. ? ? ? ? ? ? ? ? if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
  43. // ? ? ? ? ? ? ? ? ? ?throw new SecurityException();
  44. ? ? ? ? ? ? ? ? }
  45. ? ? ? ? ? ? } catch (Exception e) {
  46. ? ? ? ? ? ? ? ? e.printStackTrace();
  47. // ? ? ? ? ? ? ? ?throw new SecurityException();
  48. ? ? ? ? ? ? }
  49. ? ? ? ? }
  50.  
  51. ? ? ? ? mFd = open(device.getAbsolutePath(), baudrate, flags);
  52. ? ? ? ? if (mFd == null) {
  53. ? ? ? ? ? ? Log.e(TAG, "native open returns null");
  54. ? ? ? ? ? ? throw new IOException();
  55. ? ? ? ? }
  56. ? ? ? ? mFileInputStream = new FileInputStream(mFd);
  57. ? ? ? ? mFileOutputStream = new FileOutputStream(mFd);
  58. ? ? }
  59.  
  60. ? ? // Getters and setters
  61. ? ? public InputStream getInputStream() {
  62. ? ? ? ? return mFileInputStream;
  63. ? ? }
  64.  
  65. ? ? public OutputStream getOutputStream() {
  66. ? ? ? ? return mFileOutputStream;
  67. ? ? }
  68.  
  69. ? ? // JNI
  70. ? ? private native static FileDescriptor open(String path, int baudrate, int flags);
  71.  
  72. ? ? public native void close();
  73.  
  74. ? ? static {
  75. ? ? ? ? System.loadLibrary("serial_port");
  76. ? ? }
  77.  
  78.  
  79. }

然后clean project 再rebuild project 生成class文件,
这时候打开如下图的文件夹看是否生成了classes文件夹,没有生成请重新再试一遍。

当然你也不一定会生成compileDebugJavaWithJavac 只要javac->debug下存在classes就可以

再打开Terminal输入指令
cd app/build/intermediates/javac/debug/classes(具体位置定位到classes)
然后再输入指令
javah -jni 包名.SerialPort
注意 这里javah -jni后面跟的是 SerialPort.java 的全路径,如果javah报不存在之类的,是你的Java环境没有配置好。

这时候打开 debug/classes下面的文件发现多了一个以 .h 结尾文件

编写处理C文件

在main下创建一个jni包 将生成的.h文件复制进去

然后创建SerialPort.c文件

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <jni.h>
  4. #include <assert.h>
  5.  
  6. #include <termios.h>
  7. #include <unistd.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <string.h>
  12. #include <jni.h>
  13. #include 这里是生成.h文件全称(com_***_***_serialport_SerialPort.h)
  14.  
  15. #include "android/log.h"
  16. static const char *TAG = "serial_port";
  17. #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, ?TAG, fmt, ##args)
  18. #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
  19. #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
  20.  
  21.  
  22. static speed_t getBaudrate(jint baudrate)
  23. {
  24. ? ? switch(baudrate) {
  25. ? ? ? ? case 0: return B0;
  26. ? ? ? ? case 50: return B50;
  27. ? ? ? ? case 75: return B75;
  28. ? ? ? ? case 110: return B110;
  29. ? ? ? ? case 134: return B134;
  30. ? ? ? ? case 150: return B150;
  31. ? ? ? ? case 200: return B200;
  32. ? ? ? ? case 300: return B300;
  33. ? ? ? ? case 600: return B600;
  34. ? ? ? ? case 1200: return B1200;
  35. ? ? ? ? case 1800: return B1800;
  36. ? ? ? ? case 2400: return B2400;
  37. ? ? ? ? case 4800: return B4800;
  38. ? ? ? ? case 9600: return B9600;
  39. ? ? ? ? case 19200: return B19200;
  40. ? ? ? ? case 38400: return B38400;
  41. ? ? ? ? case 57600: return B57600;
  42. ? ? ? ? case 115200: return B115200;
  43. ? ? ? ? case 230400: return B230400;
  44. ? ? ? ? case 460800: return B460800;
  45. ? ? ? ? case 500000: return B500000;
  46. ? ? ? ? case 576000: return B576000;
  47. ? ? ? ? case 921600: return B921600;
  48. ? ? ? ? case 1000000: return B1000000;
  49. ? ? ? ? case 1152000: return B1152000;
  50. ? ? ? ? case 1500000: return B1500000;
  51. ? ? ? ? case 2000000: return B2000000;
  52. ? ? ? ? case 2500000: return B2500000;
  53. ? ? ? ? case 3000000: return B3000000;
  54. ? ? ? ? case 3500000: return B3500000;
  55. ? ? ? ? case 4000000: return B4000000;
  56. ? ? ? ? default: return -1;
  57. ? ? }
  58. }
  59.  
  60. /*
  61. ?* Class: ? ? android_serialport_SerialPort
  62. ?* Method: ? ?open
  63. ?* Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
  64. ?*/
  65. ?//这里同样是生成.h文件全称
  66. JNIEXPORT jobject JNICALL Java_com_***_***_serialport_SerialPort_open
  67. ? ? ? ? (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)
  68. {
  69. ? ? int fd;
  70. ? ? speed_t speed;
  71. ? ? jobject mFileDescriptor;
  72.  
  73. ? ? /* Check arguments */
  74. ? ? {
  75. ? ? ? ? speed = getBaudrate(baudrate);
  76. ? ? ? ? if (speed == -1) {
  77. ? ? ? ? ? ? /* TODO: throw an exception */
  78. ? ? ? ? ? ? LOGE("Invalid baudrate");
  79. ? ? ? ? ? ? return NULL;
  80. ? ? ? ? }
  81. ? ? }
  82.  
  83. ? ? /* Opening device */
  84. ? ? {
  85. ? ? ? ? jboolean iscopy;
  86. ? ? ? ? const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
  87. ? ? ? ? LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);
  88. ? ? ? ? fd = open(path_utf, O_RDWR | flags);
  89. ? ? ? ? LOGD("open() fd = %d", fd);
  90. ? ? ? ? (*env)->ReleaseStringUTFChars(env, path, path_utf);
  91. ? ? ? ? if (fd == -1)
  92. ? ? ? ? {
  93. ? ? ? ? ? ? /* Throw an exception */
  94. ? ? ? ? ? ? LOGE("Cannot open port");
  95. ? ? ? ? ? ? /* TODO: throw an exception */
  96. ? ? ? ? ? ? return NULL;
  97. ? ? ? ? }
  98. ? ? }
  99.  
  100. ? ? /* Configure device */
  101. ? ? {
  102. ? ? ? ? struct termios cfg;
  103. ? ? ? ? LOGD("Configuring serial port");
  104. ? ? ? ? if (tcgetattr(fd, &cfg))
  105. ? ? ? ? {
  106. ? ? ? ? ? ? LOGE("tcgetattr() failed");
  107. ? ? ? ? ? ? close(fd);
  108. ? ? ? ? ? ? /* TODO: throw an exception */
  109. ? ? ? ? ? ? return NULL;
  110. ? ? ? ? }
  111.  
  112. ? ? ? ? cfmakeraw(&cfg);
  113. ? ? ? ? cfsetispeed(&cfg, speed);
  114. ? ? ? ? cfsetospeed(&cfg, speed);
  115.  
  116. ? ? ? ? if (tcsetattr(fd, TCSANOW, &cfg))
  117. ? ? ? ? {
  118. ? ? ? ? ? ? LOGE("tcsetattr() failed");
  119. ? ? ? ? ? ? close(fd);
  120. ? ? ? ? ? ? /* TODO: throw an exception */
  121. ? ? ? ? ? ? return NULL;
  122. ? ? ? ? }
  123. ? ? }
  124.  
  125. ? ? /* Create a corresponding file descriptor */
  126. ? ? {
  127. ? ? ? ? jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
  128. ? ? ? ? jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
  129. ? ? ? ? jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
  130. ? ? ? ? mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
  131. ? ? ? ? (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
  132. ? ? }
  133.  
  134. ? ? return mFileDescriptor;
  135. }
  136.  
  137. /*
  138. ?* Class: ? ? cedric_serial_SerialPort
  139. ?* Method: ? ?close
  140. ?* Signature: ()V
  141. ?*/
  142. ? //这里同样是生成.h文件全称
  143. JNIEXPORT void JNICALL Java_com_***_***_serialport_SerialPort_close
  144. (JNIEnv *env, jobject thiz)
  145. {
  146. jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
  147. jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");
  148.  
  149. jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
  150. jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");
  151.  
  152. jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
  153. jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);
  154.  
  155. LOGD("close(fd = %d)", descriptor);
  156. close(descriptor);
  157. }

termios.h 具体代码:

  1. #ifndef _TERMIOS_H_
  2. #define _TERMIOS_H_
  3.  
  4. #include <sys/cdefs.h>
  5. #include <sys/ioctl.h>
  6. #include <sys/types.h>
  7. #include <stdint.h>
  8. #include <linux/termios.h>
  9.  
  10. __BEGIN_DECLS
  11.  
  12. /* Redefine these to match their ioctl number */
  13. #undef ?TCSANOW
  14. #define TCSANOW ? ?TCSETS
  15.  
  16. #undef ?TCSADRAIN
  17. #define TCSADRAIN ?TCSETSW
  18.  
  19. #undef ?TCSAFLUSH
  20. #define TCSAFLUSH ?TCSETSF
  21.  
  22. static __inline__ int tcgetattr(int fd, struct termios *s)
  23. {
  24. ? ? return ioctl(fd, TCGETS, s);
  25. }
  26.  
  27. static __inline__ int tcsetattr(int fd, int __opt, const struct termios *s)
  28. {
  29. ? ? return ioctl(fd, __opt, (void *)s);
  30. }
  31.  
  32. static __inline__ int tcflow(int fd, int action)
  33. {
  34. ? ? return ioctl(fd, TCXONC, (void *)(intptr_t)action);
  35. }
  36.  
  37. static __inline__ int tcflush(int fd, int __queue)
  38. {
  39. ? ? return ioctl(fd, TCFLSH, (void *)(intptr_t)__queue);
  40. }
  41.  
  42. static __inline__ pid_t tcgetsid(int fd)
  43. {
  44. ? ? pid_t _pid;
  45. ? ? return ioctl(fd, TIOCGSID, &_pid) ? (pid_t)-1 : _pid;
  46. }
  47.  
  48. static __inline__ int tcsendbreak(int fd, int __duration)
  49. {
  50. ? ? return ioctl(fd, TCSBRKP, (void *)(uintptr_t)__duration);
  51. }
  52.  
  53. static __inline__ speed_t cfgetospeed(const struct termios *s)
  54. {
  55. ? ? return (speed_t)(s->c_cflag & CBAUD);
  56. }
  57.  
  58. static __inline__ int cfsetospeed(struct termios *s, speed_t ?speed)
  59. {
  60. ? ? s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
  61. ? ? return 0;
  62. }
  63.  
  64. static __inline__ speed_t cfgetispeed(const struct termios *s)
  65. {
  66. ? ? return (speed_t)(s->c_cflag & CBAUD);
  67. }
  68.  
  69. static __inline__ int cfsetispeed(struct termios *s, speed_t ?speed)
  70. {
  71. ? ? s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
  72. ? return 0;
  73. }
  74.  
  75. static __inline__ void cfmakeraw(struct termios *s)
  76. {
  77. ? ? s->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
  78. ? ? s->c_oflag &= ~OPOST;
  79. ? ? s->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
  80. ? ? s->c_cflag &= ~(CSIZE|PARENB);
  81. ? ? s->c_cflag |= CS8;
  82. }
  83.  
  84. __END_DECLS
  85.  
  86. #endif /* _TERMIOS_H_ */

生成so文件

首先,在项目(app)的build.gradel中的defaultConfig下添加:

  1. externalNativeBuild {
  2. ? ? ? ? ? ? cmake {
  3. ? ? ? ? ? ? ? ? cppFlags ""
  4. ? ? ? ? ? ? ? ?// abiFilters "armeabi-v7a", "x86", "arm64-v8a"
  5. ? ? ? ? ? ? }
  6. ? ? ? ? }

然后再在项目(app)的build.gradel 的 android 闭包下添加:

  1. externalNativeBuild {
  2. ? ? ? ? cmake {
  3. ? ? ? ? ? ? path "CMakeLists.txt"?
  4. ? ? ? ? }
  5. ? ? }

在app下创建一个CMakeLists.txt

  1. # For more information about using CMake with Android Studio, read the
  2. # documentation: https://d.android.com/studio/projects/add-native-code.html
  3.  
  4. # Sets the minimum version of CMake required to build the native library.
  5.  
  6. cmake_minimum_required(VERSION 3.4.1)
  7.  
  8. # Creates and names a library, sets it as either STATIC
  9. # or SHARED, and provides the relative paths to its source code.
  10. # You can define multiple libraries, and CMake builds them for you.
  11. # Gradle automatically packages shared libraries with your APK.
  12.  
  13. #设置生成的so动态库最后输出的路径
  14. set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI})
  15.  
  16. add_library( # Sets the name of the library.
  17. ? ? ? ? #此处填入library名称,就是生成so文件的名称
  18. ? ? ? ? serial_port
  19.  
  20. ? ? ? ? # Sets the library as a shared library.
  21. ? ? ? ? SHARED
  22.  
  23. ? ? ? ? # Provides a relative path to your source file(s). c文件或cpp文件的相对路径
  24. ? ? ? ? src/main/jni/SerialPort.c
  25. ? ? ? ? )
  26. # Searches for a specified prebuilt library and stores the path as a
  27. # variable. Because CMake includes system libraries in the search path by
  28. # default, you only need to specify the name of the public NDK library
  29. # you want to add. CMake verifies that the library exists before
  30. # completing its build.
  31. find_library( # Sets the name of the path variable.
  32. ? ? ? ? log-lib
  33. ? ? ? ? # Specifies the name of the NDK library that
  34. ? ? ? ? # you want CMake to locate.
  35. ? ? ? ? log)
  36. # Specifies libraries CMake should link to your target library. You
  37. # can link multiple libraries, such as libraries you define in this
  38. # build script, prebuilt third-party libraries, or system libraries.
  39. target_link_libraries( # Specifies the target library.
  40. ? ? ? ? #此处填入library名称,就是生成so文件的名称
  41. ? ? ? ? serial_port
  42. ? ? ? ? # Links the target library to the log library
  43. ? ? ? ? # included in the NDK.
  44. ? ? ? ? ${log-lib})

你现在就可以Make Project 或者 Rebuild Project 一下 ,之后会在这里会生成so库:

把生成的so文件复制到libs下或者jniLibs下
这时so文件我们生成了就需要把build的注释掉不然下次运行还会生成

  1. externalNativeBuild {
  2. ? ? ? ? ? ? cmake {
  3. ? ? ? ? ? ? ? ? cppFlags ""
  4. ? ? ? ? ? ? ? ?// abiFilters "armeabi-v7a", "x86", "arm64-v8a"
  5. ? ? ? ? ? ? }
  6. ? ? ? ? }
  7.  
  8.  
  9. ?externalNativeBuild {
  10. ? ? ? ? cmake {
  11. ? ? ? ? ? ? path "CMakeLists.txt"?
  12. ? ? ? ? }
  13. ? ? }

然后我们封装一个SerialPortUtils

  1. import android.util.Log;
  2. import android.widget.Toast;
  3.  
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8.  
  9. /**
  10. ?* @author renquan
  11. ?*/
  12.  
  13. public class SerialPortUtils {
  14. ? ? private static SerialPortUtils serialPortUtils;
  15. ? ? private final String TAG = "SerialPortUtils";
  16. // ? ?private String path = "/dev/ttyS1";
  17. // ? ?private int baudrate = 9600;
  18. ? ? public boolean serialPortStatus = false; //是否打开串口标志
  19. ? ? public String data_;
  20. ? ? public boolean threadStatus; //线程状态,为了安全终止线程
  21. ? ? public SerialPort serialPort = null;
  22. ? ? public InputStream inputStream = null;
  23. ? ? public OutputStream outputStream = null;
  24. ? ? public ChangeTool changeTool = new ChangeTool();
  25.  
  26. ? ? public static SerialPortUtils getInstance() {
  27. ? ? ? ? if (null == serialPortUtils){
  28. ? ? ? ? ? ? serialPortUtils = new SerialPortUtils();
  29. ? ? ? ? }
  30. ? ? ? ? return serialPortUtils;
  31. ? ? }
  32.  
  33. ? ? /**
  34. ? ? ?* 获取状态
  35. ? ? ?* @return
  36. ? ? ?*/
  37. ? ? public boolean getPortStatus(){
  38. ? ? ? ? return serialPortStatus;
  39. ? ? }
  40. ? ? /**
  41. ? ? ?* 打开串口
  42. ? ? ?* @return serialPort串口对象
  43. ? ? ?*/
  44. ? ? public SerialPort openSerialPort(String path, int baudrate){
  45. ? ? ? ? if (getPortStatus()){
  46. ? ? ? ? ? ? return serialPort;
  47. ? ? ? ? }
  48. ? ? ? ? try {
  49. ? ? ? ? ? ? serialPort = new SerialPort(new File(path),baudrate,0);
  50. ? ? ? ? ? ? this.serialPortStatus = true;
  51. ? ? ? ? ? ? threadStatus = false; //线程状态
  52.  
  53. ? ? ? ? ? ? //获取打开的串口中的输入输出流,以便于串口数据的收发
  54. ? ? ? ? ? ? inputStream = serialPort.getInputStream();
  55. ? ? ? ? ? ? outputStream = serialPort.getOutputStream();
  56.  
  57.  
  58. ? ? ? ? ? ? new ReadThread().start(); //开始线程监控是否有数据要接收
  59. ? ? ? ? } catch (IOException e) {
  60. ? ? ? ? ? ? Log.d(TAG,"打开串口异常");
  61. ? ? ? ? ? ? Toast.makeText(MyApp.context, "打开串口异常", Toast.LENGTH_SHORT).show();
  62. ? ? ? ? ? ? isException = true;
  63. ? ? ? ? ? ? return serialPort;
  64. ? ? ? ? }
  65. ? ? ? ? Log.d(TAG, "openSerialPort: 打开串口");
  66. ? ? ? ? Toast.makeText(MyApp.context, "打开串口", Toast.LENGTH_SHORT).show();
  67.  
  68. ? ? ? ? return serialPort;
  69. ? ? }
  70.  
  71. ? ? /**
  72. ? ? ?* 关闭串口
  73. ? ? ?*/
  74. ? ? public void closeSerialPort(){
  75. ? ? ? ? if (!getPortStatus()){
  76. ? ? ? ? ? ? return;
  77. ? ? ? ? }
  78. ? ? ? ? if (null == inputStream || null == outputStream){
  79. ? ? ? ? ? ? Log.e(TAG, "closeSerialPort: 关闭串口异常:"+"null");
  80.  
  81. ? ? ? ? ? ? Toast.makeText(MyApp.context, "关闭串口异常", Toast.LENGTH_SHORT).show();
  82. ? ? ? ? ? ? isException = true;
  83. ? ? ? ? ? ? return;
  84. ? ? ? ? }
  85. ? ? ? ? try {
  86. ? ? ? ? ? ? inputStream.close();
  87. ? ? ? ? ? ? outputStream.close();
  88.  
  89. ? ? ? ? ? ? this.serialPortStatus = false;
  90. ? ? ? ? ? ? this.threadStatus = true; //线程状态
  91. ? ? ? ? ? ? serialPort.close();
  92. ? ? ? ? } catch (IOException e) {
  93. ? ? ? ? ? ? Log.e(TAG, "closeSerialPort: 关闭串口异常:"+e.toString());
  94. ? ? ? ? ? ? Toast.makeText(MyApp.context, "关闭串口异常", Toast.LENGTH_SHORT).show();
  95. ? ? ? ? ? ? isException = true;
  96. ? ? ? ? ? ? return;
  97. ? ? ? ? }
  98. ? ? ? ? Log.d(TAG, "closeSerialPort: 关闭串口成功");
  99. ? ? ? ? Toast.makeText(MyApp.context, "关闭串口", Toast.LENGTH_SHORT).show();
  100. ? ? }
  101.  
  102. ? ? /**
  103. ? ? ?* 发送串口指令(字符串)
  104. ? ? ?* @param data String数据指令
  105. ? ? ?*/
  106. ? ? public void sendSerialPort(String data){
  107. ? ? ? ? Log.d(TAG, "sendSerialPort: 发送数据"+data);
  108. ? ? ? ? if (null == outputStream){
  109. ? ? ? ? ? ? Log.e(TAG, "sendSerialPort: 串口数据发送失败:"+"null");
  110. ? ? ? ? ? ? Toast.makeText(MyApp.context, "串口数据发送失败", Toast.LENGTH_SHORT).show();
  111. ? ? ? ? ? ? return;
  112. ? ? ? ? }
  113. ? ? ? ? try {
  114. ? ? ? ? ? ? byte[] sendData = data.getBytes(); //string转byte[]
  115. ? ? ? ? ? ? this.data_ = new String(sendData); //byte[]转string
  116. ? ? ? ? ? ? if (sendData.length > 0) {
  117. ? ? ? ? ? ? ? ? outputStream.write(sendData);
  118. // ? ? ? ? ? ? ? ?outputStream.write('\n');
  119. // ? ? ? ? ? ? ? ?outputStream.write('\r'+'\n');
  120. ? ? ? ? ? ? ? ? outputStream.write('\r');
  121. ? ? ? ? ? ? ? ? outputStream.flush();
  122. ? ? ? ? ? ? ? ? Log.d(TAG, "sendSerialPort: 串口数据发送成功");
  123. ? ? ? ? ? ? }
  124. ? ? ? ? } catch (IOException e) {
  125. ? ? ? ? ? ? Log.e(TAG, "sendSerialPort: 串口数据发送失败:"+e.toString());
  126. ? ? ? ? ? ? Toast.makeText(MyApp.context, "串口数据发送失败", Toast.LENGTH_SHORT).show();
  127. ? ? ? ? }
  128.  
  129. ? ? }
  130.  
  131. ? ? /**
  132. ? ? ?* 单开一线程,来读数据
  133. ? ? ?*/
  134. ? ? private class ReadThread extends Thread {
  135. ? ? ? ? @Override
  136. ? ? ? ? public void run() {
  137. ? ? ? ? ? ? super.run();
  138. ? ? ? ? ? ? //判断进程是否在运行,更安全的结束进程
  139. ? ? ? ? ? ? while (!threadStatus){
  140. ? ? ? ? ? ? ? ? Log.d(TAG, "进入线程run");
  141. ? ? ? ? ? ? ? ? //64 ? 1024
  142. ? ? ? ? ? ? ? ? byte[] buffer = new byte[64];
  143. ? ? ? ? ? ? ? ? int size; //读取数据的大小
  144. ? ? ? ? ? ? ? ? try {
  145. ? ? ? ? ? ? ? ? ? ? size = inputStream.read(buffer);
  146. ? ? ? ? ? ? ? ? ? ? if (size > 0){
  147. ? ? ? ? ? ? ? ? ? ? ? ? Log.d(TAG, "run: 接收到了数据:" + changeTool.ByteArrToHex(buffer));
  148. ? ? ? ? ? ? ? ? ? ? ? ? Log.d(TAG, "run: 接收到了数据大小:" + String.valueOf(size));
  149. // ? ? ? ? ? ? ? ? ? ? ? ?onDataReceiveListener.onDataReceive(buffer,size);
  150. ? ? ? ? ? ? ? ? ? ? }
  151. ? ? ? ? ? ? ? ? } catch (IOException e) {
  152. ? ? ? ? ? ? ? ? ? ? Log.e(TAG, "run: 数据读取异常:" +e.toString());
  153. ? ? ? ? ? ? ? ? }
  154. ? ? ? ? ? ? }
  155.  
  156. ? ? ? ? }
  157. ? ? }
  158.  
  159. ? ? //数据回调
  160. ? ? public OnDataReceiveListener onDataReceiveListener = null;
  161. ? ? public static interface OnDataReceiveListener {
  162. ? ? ? ? public void onDataReceive(byte[] buffer, int size);
  163. ? ? }
  164. ? ? public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
  165. ? ? ? ? onDataReceiveListener = dataReceiveListener;
  166. ? ? }
  167.  
  168. }

常见bug

这说明我们生成的so文件有问题 那么就从头执行一次
或者说我们并没有实现so的open方法这时需要看SerialPort.java
或者打个log看看so文件内的SerialPort和我们创建的SerialPort包名是否一致

如果我们走到了这里抛出异常
说明我们的Android机器并没有root无法访问权限这时我们需要找到厂商改下系统
或者系统给了权限但是我们并没有添加

  1. <!--往sdcard中写入数据的权限 -->
  2. ? ? <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  3. ? ? <!--在sdcard中创建/删除文件的权限 -->
  4. ? ? <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

*注意

由于设备不同文件路径有不同
这里默认的是/system/bin/su
有的机型路径是/system/xbin/su

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号