android串口通信
JNI代码生成,可以直接使用android-serialport-api 里面jni文件夹,里面已经有Android.mk文件了,直接编译。编译出来libserial_port.so 可以在5.0上正常使用,在android7.0上就会报错
UnsatisfiedLinkError和libserial_port.so: has text relocations异常修改Android.mk文件,不进行校验
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) TARGET_PLATFORM := android-3 LOCAL_MODULE := serial_port LOCAL_SRC_FILES := SerialPort.c LOCAL_LDLIBS := -llog LOCAL_MULTILIB := 32 LOCAL_LDFLAGS +=-fPIC //++ include $(BUILD_SHARED_LIBRARY)编译出来: libserial_port.so 注意编译是32位,如果编译成64位的话,到时链接时要看一下是在arm包中找的还是在arm64中找的,如果是arm64则需要编译成64位
2.java代码建立通信
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; /** * Google官方代码 * 此类的作用为,JNI的调用,用来加载.so文件的 * 获取串口输入输出流 */ 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 777 " + 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(); } } System.out.println(device.getAbsolutePath() + "==============================");*/ 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(调用java本地接口,实现串口的打开和关闭) /**串口有五个重要的参数:串口设备名,波特率,检验位,数据位,停止位 其中检验位一般默认位NONE,数据位一般默认为8,停止位默认为1*/ /** * @param path 串口设备的据对路径 * @param baudrate 波特率 * @param flags 校验位 */ private native static FileDescriptor open(String path, int baudrate, int flags); public native void close(); static { System.out.println("=============================="); System.loadLibrary("serial_port"); System.out.println("********************************"); } }我们可以通过读流和写流进行串口通信了,就这么简单。
3.权限问题
按照上面步骤操作,可能会提醒设备节点打开失败,是权限导致。
如何验证权限问题: 例如串口节点为/dev/ttyHSL
1.首先对ttyHSL chmod 777 修改节点权限修改
2.然后可能会报SELinux权限问题,如何修改:SELinux权限修改
需要具体Demo代码,可以留言,私信给你github链接
