1. 程式人生 > >Android 串列埠通訊自定義生成so檔案

Android 串列埠通訊自定義生成so檔案

串列埠通訊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下面


為了專案包名的一致性,不想用Google的包名,全部用自己的包名,這個時候就要自己生成so檔案了,下面講解怎麼自己生成so檔案。首先在Android Studio新建一個支援C/C++的專案



注意要勾選紅框中的內容新建好的工程:會幫我們新建好兩個檔案,native-lib.cpp 和CMakeLists.txt


將下載的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檔名,記住這個名,後面要用到

此時專案結構如下:


下面一步就是要生成 C語言標頭檔案

開啟 Terminal(View -> Tool Windows -> Terminal)


輸入cd app\src\main\java進入原始碼所在目錄


輸入javah com.test.myapplication.SerialPort生成標頭檔案



將前面生成的 .h 檔案移入cpp資料夾中,右鍵cpp選單中選擇New -> C/C++ Source File建立與 .h 檔案同名的 .c 檔案


將下載的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);
}


刪除紅色部分報錯的問題,點選右上角的Sync Now,成功之後下一步就要要配置NDK,生成so檔案,這裡用到的是CMakeLists.txt


主要就是講紅色框中的內容修改為我們上面的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檔案。


到這裡就基本可以over了,最後我們點選Build--->Make Project,成功之後我們會在app\build\intermediates\cmake\debug\obj各個平臺目錄下看到已經生成了so檔案。