提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
最近需要在上层app使用串口,发送指令对底层硬件进行操作,因此需要将Android串口移植到代码中
一、移植java文件
路径如下:pro\app\src\main\java\android_serialport_api
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";
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
if (!device.canRead() || !device.canWrite()) {
try {
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);
}
public InputStream getInputStream() {
return mFileInputStream;
}
public OutputStream getOutputStream() {
return mFileOutputStream;
}
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"
}
还有一些配置
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(使用前将#替换为@)