最近有两个项目用到了串口通信,就在网上找了些串口通信的资料研究了下。Android的串口通信分为两种方式,一种是开发系统app就可以直接调用 android.hardware.SerialManager, android.hardware.SerialPort这两个类完成串口通信。由于这两个类不对应该层提供,所以下面主要讲讲第二种方式,用jni完成对串口的操作。
1:AS配置ndk开发环境(这个比较简单,不会的可以问问度娘);
2:编写串口类
import android.util.Log; import com.tiannuo.usbandserialapi.utils.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 = "android_serialport_api"; /* * 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 { try { System.loadLibrary("serial_port"); }catch (Exception e){ LOG.e("loadLibrary error"); } } }3:make生成头文件;
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class android_serialport_api_SerialPort */ #ifndef _Included_android_serialport_api_SerialPort #define _Included_android_serialport_api_SerialPort #ifdef __cplusplus extern "C" { #endif /* * Class: android_serialport_api_SerialPort * Method: open * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor; */ JNIEXPORT jobject JNICALL Java_android_1serialport_1api_SerialPort_open (JNIEnv *, jclass, jstring, jint, jint); /* * Class: android_serialport_api_SerialPort * Method: close * Signature: ()V */ JNIEXPORT void JNICALL Java_android_1serialport_1api_SerialPort_close (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif4:根据文件编写C文件