最近开发Android的过程中需要通过C来调用Android终端中的某些API,而我是用JAVA语言来开发的Android程序,所以就需要用到JNI调用。
流程是,用C来调用Android硬件接口,约定JAVA调用C的接口,然后把这些代码封装编译成.so文件。然后就是怎么引入与调用了。
1、将.so文件加入到libs目录下,.so文件命名规范为lib*,lib后加上名字。
2、加入jniLibs路径配置,在build.gradle中加入如下配置:
android { …… sourceSets { main { jniLibs.srcDirs = [‘libs‘] } } }
3、JAVA调用
public class UspJni { private final static String TAG = "USPJNI"; static { try{ System.loadLibrary("uspjni");//加载libuspjni.so Log.d(TAG, "libuspjni.so load"); }catch(Exception e){ System.err.println("Native code library failed to load.\n"+e); } } public static UspJni getInstance() { if (jni == null) { jni = new UspJni(); } return jni; } public int uartOpen(String path, int flags) { Log.d(TAG, "(uartOpen)path=" + path + ",flags=" + String.valueOf(flags)); uartFd = this.open(path, flags); if (uartFd < 0) { Log.d(TAG, "(uartOpen)failed" + ",uartFd=" + String.valueOf(uartFd)); } return uartFd; } public int uartClose() { Log.d(TAG, "(uartClose)"); int status = this.close(uartFd); uartFd = -1; if (status != 0) { Log.d(TAG, "(uartClose)failed,status=" + String.valueOf(status) + ",uartFd=" + uartFd); } return status; } public byte[] uartRead(int timeout) { Log.d(TAG, "(uartRead)timeout=" + timeout); byte[] buff = this.read(uartFd,timeout); if (buff==null) { return new byte[0]; } Log.d(TAG, "(uartRead)len=" + buff.length); return buff; } public int uartFlush() { Log.d(TAG, "(uartFlush)"); byte[] data; do { data = UspJni.getInstance().uartRead(50);//调用 }while(data.length>0); return 0; } public native int gpioSetStatus(int ioId, int status); public native int gpioGetStatus(int ioId); private native int open(String path, int flags); private native int close(int fd); private native byte[] read(int fd,int timeout); private native int write(int fd, byte[] data, int count); private static UspJni jni; private UspJni() { } }
时间: 2024-10-08 17:15:48