Android 串口通信自定义生成so文件

时间:2022-07-22 05:23:23

串口通信Android设备通过串口与其他设备进行通信的一种方式,对于Android串口操作基本上就是对应串口文件的读写,基本思路就是: 

1.对串口文件进行配置(波特率等),打开串口文件 
2.读写串口 
3.关闭串口文件 

但是这里需要注意的是Android中读写串口需要用到FileDescriptor类(文件描述符)

关于串口通信,Google已经给出了源码,具体地址如下:https://github.com/cepr/android-serialport-api,大家可以自行下载使用,直接使用时因为他已经将so已经打包生成好了,所以要保留Google原本的包名才行,如果不保留Google原本的包名你将.so放在你的项目中你会发现是不能使用的,原因是因为so中的方法名是通过开源项目的包名+方法名来的。放在你项目中包名都变了,所以so文件将无法找到对应的方法的,用Google原本so项目结构如下,注意加载so文件的SerialPort.java类一定要位于Google原本的包名android_serialport_api下面

Android 串口通信自定义生成so文件

为了项目包名的一致性,不想用Google的包名,全部用自己的包名,这个时候就要自己生成so文件了,下面讲解怎么自己生成so文件。首先在Android Studio新建一个支持C/C++的项目

Android 串口通信自定义生成so文件

Android 串口通信自定义生成so文件

注意要勾选红框中的内容新建好的工程:会帮我们新建好两个文件,native-lib.cpp 和CMakeLists.txt

Android 串口通信自定义生成so文件

将下载的Google源码包中的SerialPort.java 类,添加到项目中

import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort {
    private static final String TAG = "SerialPort";  

    /* 
     * Do not remove or rename the field mFd: it is used by native method close(); 
     */  
    private FileDescriptor mFd;  
    private FileInputStream mFileInputStream;  
    private FileOutputStream mFileOutputStream;  

    public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {  

        /* Check access permission */  
        if (!device.canRead() || !device.canWrite()) {  
            try {  
                /* Missing read/write permission, trying to chmod the file */  
                Process su;  
                su = Runtime.getRuntime().exec("/system/bin/su");  
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"  
                        + "exit\n";  
                su.getOutputStream().write(cmd.getBytes());  
                if ((su.waitFor() != 0) || !device.canRead()  
                        || !device.canWrite()) {  
                    throw new SecurityException();  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new SecurityException();  
            }  
        }  

        mFd = open(device.getAbsolutePath(), baudrate, flags);  
        if (mFd == null) {  
            Log.e(TAG, "native open returns null");  
            throw new IOException();  
        }  
        mFileInputStream = new FileInputStream(mFd);  
        mFileOutputStream = new FileOutputStream(mFd);  
    }  

    // Getters and setters  
    public InputStream getInputStream() {  
        return mFileInputStream;  
    }  

    public OutputStream getOutputStream() {  
        return mFileOutputStream;  
    }  

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

修改最后一部分

 static {  
        System.loadLibrary("twaer_control");  
    }  

"twaer_control"是自定义的要生成的so文件名,记住这个名,后面要用到

此时项目结构如下:

Android 串口通信自定义生成so文件

下面一步就是要生成 C语言头文件

打开 Terminal(View -> Tool Windows -> Terminal)

Android 串口通信自定义生成so文件

输入cd app\src\main\java进入源码所在目录

Android 串口通信自定义生成so文件

输入javah com.test.myapplication.SerialPort生成头文件

Android 串口通信自定义生成so文件

Android 串口通信自定义生成so文件

将前面生成的 .h 文件移入cpp文件夹中,右键cpp菜单中选择New -> C/C++ Source File创建与 .h 文件同名的 .c 文件

Android 串口通信自定义生成so文件

将下载的Google源码包中的SerialPort.c 类拷贝到com_test_myapplication_SerialPort.c中

/*
 * Copyright 2009-2011 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>

#include "SerialPort.h"

#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 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:     android_serialport_SerialPort
 * Method:    open
 * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
 */
JNIEXPORT jobject JNICALL Java_android_1serialport_1api_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) {
			/* TODO: throw an exception */
			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");
			/* TODO: throw an exception */
			return NULL;
		}
	}

	/* Configure device */
	{
		struct termios cfg;
		LOGD("Configuring serial port");
		if (tcgetattr(fd, &cfg))
		{
			LOGE("tcgetattr() failed");
			close(fd);
			/* TODO: throw an exception */
			return NULL;
		}

		cfmakeraw(&cfg);
		//设置波特率
		cfsetispeed(&cfg, speed);
		cfsetospeed(&cfg, speed);

		if (tcsetattr(fd, TCSANOW, &cfg))
		{
			LOGE("tcsetattr() failed");
			close(fd);
			/* TODO: throw an exception */
			return NULL;
		}
	}

	/* Create a corresponding file descriptor */
	{
		jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
		jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()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:     cedric_serial_SerialPort
 * Method:    close
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_android_1serialport_1api_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);
}

Android 串口通信自定义生成so文件

删除红色部分报错的问题,点击右上角的Sync Now,成功之后下一步就要要配置NDK,生成so文件,这里用到的是CMakeLists.txt

Android 串口通信自定义生成so文件

主要就是讲红色框中的内容修改为我们上面的c文件名称,其中1、3都是上面SerialPort.java中设置的生成so文件名,1和3两个ya保持一致,2是上面的c文件。接下来再看下build.gradle的配置改变:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.test.myapplication"
        minSdkVersion 18
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', "x86", "x86_64", "arm64-v8a"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
主要多了两个地方的改变:

1:defaultConfig中添加:

externalNativeBuild {  
            cmake {  
                cppFlags ""  
            }  
        }  

2:在android{}中添加:

externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}

3:配置so文件生成平台

 ndk {
            abiFilters 'armeabi', 'armeabi-v7a', "x86", "x86_64", "arm64-v8a"
        }

点击右上角的Sync Now,成功后我们可以在app\build\intermediates\cmake\debug\obj目录下看到生成了我们之前设置的平台目录,但里面还没有so文件。

Android 串口通信自定义生成so文件

到这里就基本可以over了,最后我们点击Build--->Make Project,成功之后我们会在app\build\intermediates\cmake\debug\obj各个平台目录下看到已经生成了so文件。

Android 串口通信自定义生成so文件