之前写的东西太乱了,最近再次使用的时候发现本可以很简单的。

=================

首先,建一个android工程,选上Include c++ support选项。

之所以这样做是因为,这样会生成一个CMakeLists.txt的文件,后面我们会修改这个文件。

在工程目录app\src\main\cpp中有一个文件名文native-lib.cpp的文件,其中CMakeLists.txt就是编译这个cpp文件的依据。

如果我们加入工程的cpp文件或者c文件名字不同,则需要修改CMakeLists.txt的内容。

------------------------------------------------

其次,加入android-serialport-api类中的2个文件,文件名是SerialPort.java和SerialPortFinder.java。

再写一个自己使用或者说测试用的类。

public class MySerialPort {    private static Context mContext;    private static SerialPort mSerialPort;    private static InputStream mInputStream;    private static OutputStream mOutputStream;    public MySerialPort(Context ctx) {        mContext = ctx;    }    public static void openSerialPort(Context ctx) {        if (mSerialPort == null) {            try {                /* Open serial port */                mSerialPort = new SerialPort(new File("/dev/ttyAMA4"), 115200, 0);                mOutputStream = mSerialPort.getOutputStream();                mInputStream = mSerialPort.getInputStream();                /* Start read serial port thread */                mOutputStream.write('a');                new RecvThread().start();            } catch (IOException e) {                Toast.makeText(ctx, "打开失败", Toast.LENGTH_SHORT).show();                e.printStackTrace();            }        } else {            /* Close serial port */            mSerialPort.close();            mSerialPort = null;        }    }    public void close() {        mSerialPort.close();        mSerialPort = null;    }    private static class RecvThread extends Thread {        @Override        public void run() {            super.run();      //接收的数据处理        }    }
}

------------------------------------------------

再次,只要在MainActivity中调用自己自定义的MySerialPort即可。

如:

MySerialPort mySerialPort = new MySerialPort(this);mySerialPort.openSerialPort(this);

------------------------------------------------

最后,也是很重要的.c文件和.h文件  文件名是serial_port.c

#include "termios.h"#include #include #include #include #include #include #include "android/log.h"static const char *TAG="serial_port";#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO,  TAG, fmt, ##args)#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)static __inline__ int tcgetattr1(int fd, struct termios *s){    return ioctl(fd, TCGETS, s);}static __inline__ int tcsetattr1(int fd, int __opt, const struct termios *s){    return ioctl(fd, __opt, (void *)s);}static __inline__ void cfmakeraw1(struct termios *s){    s->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);    s->c_oflag &= ~OPOST;    s->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);    s->c_cflag &= ~(CSIZE|PARENB);    s->c_cflag |= CS8;}static __inline__ int cfsetispeed1(struct termios *s, speed_t  speed){    s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);    return 0;}static __inline__ int cfsetospeed1(struct termios *s, speed_t  speed){    s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);    return 0;}static speed_t getBaudrate(jint baudrate){    switch(baudrate) {        case 0: return B0;        case 50: return B50;        case 75: return B75;        case 110: return B110;        case 134: return B134;        case 150: return B150;        case 200: return B200;        case 300: return B300;        case 600: return B600;        case 1200: return B1200;        case 1800: return B1800;        case 2400: return B2400;        case 4800: return B4800;        case 9600: return B9600;        case 19200: return B19200;        case 38400: return B38400;        case 57600: return B57600;        case 115200: return B115200;        case 230400: return B230400;        case 460800: return B460800;        case 500000: return B500000;        case 576000: return B576000;        case 921600: return B921600;        case 1000000: return B1000000;        case 1152000: return B1152000;        case 1500000: return B1500000;        case 2000000: return B2000000;        case 2500000: return B2500000;        case 3000000: return B3000000;        case 3500000: return B3500000;        case 4000000: return B4000000;        default: return -1;    }}/* * Class:     com_leon_androidserialportapi_SerialPort * Method:    open * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor; */JNIEXPORT jobject JNICALL Java_com_rain60w_ddagreement_serial_SerialPort_open        (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags){    int fd;    speed_t speed;    jobject mFileDescriptor;    /* Check arguments */    {        speed = getBaudrate(baudrate);        if (speed == -1) {            LOGE("Invalid baudrate");            return NULL;        }    }    /* Opening device */    {        jboolean iscopy;        const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);        LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);        fd = open(path_utf, O_RDWR | flags);        LOGD("open() fd = %d", fd);        (*env)->ReleaseStringUTFChars(env, path, path_utf);        if (fd == -1)        {            /* Throw an exception */            LOGE("Cannot open port");            return NULL;        }    }    /* Configure device */    {        struct termios cfg;        LOGD("Configuring serial port");        if (tcgetattr1(fd, &cfg))        {            LOGE("tcgetattr1() failed");            close(fd);            return NULL;        }        cfmakeraw1(&cfg);        cfsetispeed1(&cfg, speed);        cfsetospeed1(&cfg, speed);        if (tcsetattr1(fd, TCSANOW, &cfg))        {            LOGE("tcsetattr1() failed");            close(fd);            return NULL;        }    }    /* Create a corresponding file descriptor */    {        jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");        jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "", "()V");        jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");        mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);        (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);    }    return mFileDescriptor;}/* * Class:     com_leon_androidserialportapi_SerialPort * Method:    close * Signature: ()V */JNIEXPORT void JNICALL Java_com_rain60w_ddagreement_serial_SerialPort_close(JNIEnv * env, jobject thiz){jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);LOGD("close(fd = %d)", descriptor);close(descriptor);}
其中,
Java_com_rain60w_ddagreement_serial_SerialPort_close和
Java_com_rain60w_ddagreement_serial_SerialPort_open

函数名改成自己放入SerialPort.java和SerialPortFinder.java两个文件的目录名。

我这个所在的目录是com.rain60w.ddagreement.serial。 所以c文件函数名就用上面的那个。 

原因是在SerialPort.java中使用了

// JNIprivate native static FileDescriptor open(String path, int baudrate, int flags);public native void close();static {    System.loadLibrary("serial_port");}

这个。 

再贴出.h文件   文件名是termios.h

#ifndef _TERMIOS_H_
#define _TERMIOS_H_


#include
#include
#include
#include
#include


__BEGIN_DECLS


/* Redefine these to match their ioctl number */
#undef  TCSANOW
#define TCSANOW    TCSETS


#undef  TCSADRAIN
#define TCSADRAIN  TCSETSW


#undef  TCSAFLUSH
#define TCSAFLUSH  TCSETSF


static __inline__ int tcgetattr(int fd, struct termios *s)
{
    return ioctl(fd, TCGETS, s);
}


static __inline__ int tcsetattr(int fd, int __opt, const struct termios *s)
{
    return ioctl(fd, __opt, (void *)s);
}


static __inline__ int tcflow(int fd, int action)
{
    return ioctl(fd, TCXONC, (void *)(intptr_t)action);
}


static __inline__ int tcflush(int fd, int __queue)
{
    return ioctl(fd, TCFLSH, (void *)(intptr_t)__queue);
}


static __inline__ pid_t tcgetsid(int fd)
{
    pid_t _pid;
    return ioctl(fd, TIOCGSID, &_pid) ? (pid_t)-1 : _pid;
}


static __inline__ int tcsendbreak(int fd, int __duration)
{
    return ioctl(fd, TCSBRKP, (void *)(uintptr_t)__duration);
}


static __inline__ speed_t cfgetospeed(const struct termios *s)
{
    return (speed_t)(s->c_cflag & CBAUD);
}


static __inline__ int cfsetospeed(struct termios *s, speed_t  speed)
{
    s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
    return 0;
}


static __inline__ speed_t cfgetispeed(const struct termios *s)
{
    return (speed_t)(s->c_cflag & CBAUD);
}


static __inline__ int cfsetispeed(struct termios *s, speed_t  speed)
{
    s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
  return 0;
}


static __inline__ void cfmakeraw(struct termios *s)
{
    s->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
    s->c_oflag &= ~OPOST;
    s->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
    s->c_cflag &= ~(CSIZE|PARENB);
    s->c_cflag |= CS8;
}


static __inline int cfsetspeed(struct termios* s, speed_t speed) {
  // TODO: check 'speed' is valid.
  s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
  return 0;
}


//static __inline int tcdrain(int fd) {
//  // A non-zero argument to TCSBRK means "don't send a break".
//  // The drain is a side-effect of the ioctl!
//  return ioctl(fd, TCSBRK, __BIONIC_CAST(static_cast, unsigned long, 1));
//}


__END_DECLS


#endif /* _TERMIOS_H_ */


再附上改过的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            )# 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} )
我想这下都完整了。

更多相关文章

  1. Android(安卓)assets 目录介绍和应用
  2. Android布局整合include界面控件
  3. android-实现黑名单拦截
  4. Android(安卓)选择文件并获取路径
  5. android_1
  6. Android(安卓)logback代码配置详解
  7. Android文件存储--采用SharedPreferences保存用户偏好设置参数和
  8. AndroidManifest.xml文件综合详解
  9. FFmpeg编程开发笔记 —— Android(安卓)FFmpeg + SDL2.0简易播放

随机推荐

  1. Android(安卓)AIDL(Android(安卓)Interfa
  2. Android P Wifi Enable 之后扫描流程
  3. Android Studio中引入layoutlibjar的正确
  4. android目录结构介绍(寒假学习1)
  5. BackHandler是全局的!!!
  6. android安装app
  7. ch07 Android 回调方法
  8. Android客户端性能测试
  9. android 项目收获02
  10. android 代码创建快捷方式