Android串口的使用(转载+移植)

2023-05-16

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、移植java文件
  • 二、移植jni文件
  • 总结


前言

最近需要在上层app使用串口,发送指令对底层硬件进行操作,因此需要将Android串口移植到代码中

一、移植java文件

在这里插入图片描述
路径如下:pro\app\src\main\java\android_serialport_api

/*
 * Copyright 2009 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. 
 */

package android_serialport_api;

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("SerialPort");
	}
}

二、移植jni文件

在这里插入图片描述
cmake添加如下

add_library(SerialPort
        SHARED
        SerialPort.c)

find_library(
        log-lib
        log)

target_link_libraries(
        SerialPort
        ${log-lib})

这里有一个坑,注意:修改成7版本,4版本会报ndk错误
build.gradle(Project)

    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

还有一些配置

    defaultConfig {
		。。。
        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a'
        }
    }
    
    externalNativeBuild {
        cmake {
            path "src/main/jni/CMakeLists.txt"
        }
    }

还有一些其他的步骤,建议参考这篇文章
https://blog.csdn.net/itdo_just/article/details/80514116
具体使用如下:(这里是写入命令)

        try {
            SerialPort mSerialPort = new SerialPort(new File("/dev/" + "ttyXRUSB2"), 1500000, 0);
            InputStream mInputStream = mSerialPort.getInputStream();
            String content;
            
            if(enabled == true){
                content = "3308_audio &\r\n";
            }else {
                content = "killall -9 3308_audio\r\n";
            }
            
            byte[] bytes = content.getBytes();
            OutputStream out = (FileOutputStream) mSerialPort.getOutputStream();
            // 写入数据
            out.write(bytes);
            out.flush();
            out.close();
            mSerialPort.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

总结

参考的主要博客为:https://blog.csdn.net/itdo_just/article/details/80514116

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android串口的使用(转载+移植) 的相关文章

随机推荐