说明
开源库: https://github.com/cepr/android-serialport-api
- 参照AS的带C方式创建cpp文件夹,记得把配置也加上。
- 把开源库中的 SerialPort.c 和 SerialPort.h 拷贝下来,放入cpp文件夹中
- 创建CMake文件,我这里直接拷贝的AS的 CMakeLists.txt
经过以上3步,基本工作就做完了,这时候你的cpp库有3个文件: CMakeLists.txt 文件, c文件和头文件。
然后剩下的就是定义调用串口的文件了
修改代码
修改SerialPort头文件和C代码
以下是 SerialPort.c 文件,除了输出的 JNICALL 基本没啥要改的
- 格式是
Java_包名_类名_方法名
,用下划线隔开- 下面要创建的java类及方法一定要严格对应
- 头文件和C代码的 JNICALL 保持同名
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_xc_autopoct_debugtool_utils_config_SerialPort */
#ifndef _Included_com_xc_autopoct_debugtool_utils_config_SerialPort
#define _Included_com_xc_autopoct_debugtool_utils_config_SerialPort
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_xc_autopoct_debugtool_utils_config_SerialPort
* Method: open
* Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
*/
JNIEXPORT jobject JNICALL Java_com_xc_autopoct_debugtool_utils_config_SerialPort_open
(JNIEnv *, jclass, jstring, jint, jint);
/*
* Class: com_xc_autopoct_debugtool_utils_config_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_xc_autopoct_debugtool_utils_config_SerialPort_close
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
修改CMake文件
-
add_library
- 1参设置库名(你要在java中加载的库名称),
- 2参设置共享(基本都是SHARE),
- 3参设置源文件的相对路径(因为在同一目录下,直接写文件名即可)
-
find_library
这个东西我也没搞明白,看说明是用来搜索库路径的,但是因为有默认值,所以只需要指定NDK就行了,而且删了也不影响什么
-
target_link_libraries
- 1参指定目标库,就是上面设置的库
- 2参用来连接到日志库,已经包含在nkd中了,如果你的 find_library 默认的话,这里也默认就行了,如果 find_library 删掉的话,这里也删掉
点击build构建一下,可能会出现一下问题:
将gradle的版本3.1.2改成3.2.1,我这边就解决了,再点击build构建一下,就可以在app/build/cmake/debug/obj路径下看到生成的so库了,大功告成!