您好,登錄后才能下訂單哦!
最近開發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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。