Android 串口通信

GitHub上的源码,是Eclipse文件结构

https://github.com/cepr/android-serialport-api

在AS中需要这样做

第一步:将工程目录切换为Project

这里写图片描述

第二部:创建libs和jni文件目录(如果没有的话)

libs在app根目录下
这里写图片描述

jni在main文件下,可以这样创建
这里写图片描述

如果这时候你切换回Android目录时会发现目录变成这样
这里写图片描述
cpp就是jni目录

第三部:将GitHub上工程的libs和jni文件全部拷贝到我们的工程的目录中
这里写图片描述

第四部:将GitHub上工程的SerialPort.java放到我们的工程中,SerialPortFinder.java可以不要,只是一个工具类

这里写图片描述

这里写图片描述

注意包名,如果你不修改jni里面的东西,那么包名只能这么写,SerialPortUtil是我自己写的一个工具类

移植的工作就这么多了,到此时为止,程序肯定跑不起来的

那么我们再看看还需要啥

app的build.gradle的配置

这里写图片描述

project目录下的gradle.properties,添加android.useDeprecatedNdk=true

# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.useDeprecatedNdk=true

下载安装配置ndk

这里写图片描述

还有一点,开发环境版本为25的时候会出错,建议大于或小于这个版本,最后再说一点,在SerialPort.java文件中如果

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);
}

打开串口失败,请将

su = Runtime.getRuntime().exec("/system/bin/su");
改为
su = Runtime.getRuntime().exec("/system/xbin/su");

可把我给坑惨了。

猜你喜欢

转载自blog.csdn.net/a598068693/article/details/77840380