本文主要介绍,如何在自己的AndroidStudio项目中引入Google开源的串口通信方案(android-serialport-api)
完整项目地址 https://github.com/Micheal-Yan/ImportDemo
Google开源的方案项目地址 https://github.com/cepr/android-serialport-api
演示如何与自动售货机建立串口通信,从而达到控制自动售货机的目的 https://github.com/Micheal-Yan/FuJiTestDemo
1,在使用AndroidStudio创建新项目时,勾选Include C++ support
2,将Google官方Demo代码中SerialPort.java和SerialPortFinder.java这两个Java文件,直接拷贝到我们的项目中来
3,打开SerialPort.java文件,将光标分别移至open和close方法上,然后按住Alt+Enter快捷键,选择"Create function xxx"快捷方式,将会自动为我们在native-lib.cpp文件中,为我们创建对应的jni方法
4,将Google官方Demo代码中serial_port.h和serial_port.c这两个C源文件,分别拷贝的项目的cpp/include和cpp目录下,并修改jni方法签名为上一步编译器自动生成签名
5,修改CMakeLists.txt内容如下
# 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.
serial_port
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/serial_port.c )
# Specifies a path to native header files.
include_directories(src/main/cpp/include/)
# 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.
serial_port
# Links the target library to the log library
# included in the NDK.
${log-lib} )