Android NDK 实现串口工具

实现效果

在这里插入图片描述

SerialPort.c

将 SerialPort.c 放入 src/main/cpp 目录中。

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.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)

/* 
* Class: android_serialport_SerialPort 
* Method: open 
* Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor; 
*/
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_com_test_serialtool_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_com_test_serialtool_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);
}

CMakeLists.txt

CmakeLists.txt 与 SerialPort.c 在同一目录下。

cmake_minimum_required(VERSION 3.4.1)

add_library(
        serial_port
        SHARED
        SerialPort.c
)

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 )

target_link_libraries(
        serial_port
        ${
   log-lib}
)

build.gradle

在 android {} 中添加:

//    支持ndk,加载cmake文件
externalNativeBuild {
   
     cmake {
   
         path file('src/main/cpp/CMakeLists.txt')
     }
 }

SerialPort.java

SerialPort.java 的包名需与 SerialPort.c 中声明的一致。

package com.test.serialtool;

import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 该类的包名需与生成so时设置的包名相同
 */
public class SerialPort {
   

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

    public native void close();

    public native FileDescriptor open(String var1, int var2, int var3);

    private File mDevice = null;
    private int mBaudrate;
    private FileDescriptor mFd = null;
    private boolean isConnected = false;
    private FileInputStream mFileInputStream = null;
    private FileOutputStream mFileOutputStream = null;

    public FileInputStream getInputStream() {
   
        return this.mFileInputStream;
    }

    public FileOutputStream getOutputStream() {
   
        return this.mFileOutputStream;
    }

    public SerialPort(File device, int baudrate) throws SecurityException, IOException {
   
        if (device == null) {
   
            Log.e("SerialPort", "device not null");
            throw new IOException();
        } else {
   
            if (!device.canRead() || !device.canWrite()) {
   
                try {
   
                    Process su = Runtime.getRuntime().exec("/system/bin/su");
                    String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                    su.getOutputStrea
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android NDKAndroid开发工具的一部分,它允许开发者使用C或C++语言编写原生代码,以便实现更高效和更复杂的功能。而串口通信是一种通过串口接口实现数据传输的方式,常见于嵌入式系统和电子设备之间的通信。 Android NDK提供了对串口通信的支持,开发者可以使用JNI调用C或C++代码来实现串口通信功能。通过NDK的JNI接口,开发者可以调用已经封装好的串口库,或者自己编写串口通信的相关代码。在UE8B项目中,我利用Android NDK的编译器将C代码通过JNI接口与Java代码进行交互,成功实现串口通信的功能。 在使用Android NDK进行串口通信时,需要先在NDK配置文件Android.mk中指定源文件路径、编译选项和目标库类型等。然后,使用Android Studio进行项目编译和构建。在Java代码中,通过调用JNI接口函数,可以实现与C或C++代码的交互,从而完成串口通信的功能。 对于串口通信,需要了解串口的相关知识,括波特率、数据位、校验位、停止位等参数的设置。在具体的应用场景中,我们可以根据需要进行相应的串口设置。通过使用NDK的相关接口,我们可以在Android平台上实现串口通信功能,从而满足特定需求。 总之,Android NDK提供了一种使用C或C++语言在Android平台上实现串口通信功能的方法。通过JNI接口,我们可以将Java代码和C代码进行交互,从而实现更高效和更复杂的串口通信功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值