最近开发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() { } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。