君问归期未有期,巴山夜雨涨秋池。
对于Android串口的使用,基本已经被写烂了,网上一搜一大堆教程,还有很多大佬也已经封装成库了,可以在项目中直接添加依赖进行使用。用别人造的轮子不好吗?非要自己动手再造轮子?这是在弄啥嘞?
emm。。。。。这么一说好像这篇文章没必要往下写了。。。。。。
别人造的轮子https://github.com/xmaihh/Android-Serialport
这个轮子造的不错,但是有个小瑕疵,如果使用默认的粘包处理,默认的是不处理粘包,直接读取返回,但是在返回数据的时候,将数据位扩展成64位了,对于接收数据量比较少的数据,会产生很多 多余的“0”。
问题是出现在BaseStickPackageHelper里面
//原来定义的数据
byte[] buffer = new byte['?'];
//可以改成这样
byte[] buffer = new byte[available];
好了,是时候打脸了,我要往下写了,谁让咱们是勤写标兵呢
这篇文章其实是接着我上一篇文章的,Android串口使用2之使用Google官方库android-serialport-api 它是用Android.mk方式实现的,而这篇文章用CMake工具也可以做到,反正最后都能抓到老鼠,至于它是黑猫、白猫还是红猫,那就要看你怎么看咯。
由于Android Studio 3.5版本在新建项目之时,无法看到Include C++ Support这个选项,本来可以一步到位的操作,现在要多走几步了。
检查NDK和CMake是否安装# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
SerialPort
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/jni/SerialPort.c)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log)
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
SerialPort
# Links the target library to the log library
# included in the NDK.
${log-lib})
CMakeLists.txt这个文件主要定义了哪些文件需要编译,以及和其他库的关系等。
右键app,选择Link C++ Project with GradleexternalNativeBuild {
cmake {
path file('CMakeLists.txt')
}
}
但是还需要手动添加一点内容
defaultConfig {
......
externalNativeBuild {
cmake {
cppFlags ""
//.so文件所支持的CPU架构
abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86_64', 'x86'
}
}
}
目前Android系统支持以下七种不用的CPU架构,每一种对应着各自的应用程序二进制接口ABI:(Application Binary Interface)定义了二进制文件(尤其是.so文件)如何运行在相应的系统平台上,从使用的指令集,内存对齐到可用的系统函数库。对应关系如下:
ARMv5——armeabi
ARMv7 ——armeabi-v7a
ARMv8——arm64-v8a
x86——x86
MIPS ——mips
MIPS64——mips64
x86_64——x86_64
static {
System.loadLibrary("SerialPort");
}
写到这里,基本就完成了android-serialport-api库的移植,感觉所做的事情也不少,就当学习下新技能,CMake工具的简单使用。
如果需要源代码的,可以点这里。
源代码