您好,登錄后才能下訂單哦!
最近開發(fā)Android的過程中需要通過C來調(diào)用Android終端中的某些API,而我是用JAVA語言來開發(fā)的Android程序,所以就需要用到JNI調(diào)用。
流程是,用C來調(diào)用Android硬件接口,約定JAVA調(diào)用C的接口,然后把這些代碼封裝編譯成.so文件。然后就是怎么引入與調(diào)用了。
1、將.so文件加入到libs目錄下,.so文件命名規(guī)范為lib*,lib后加上名字。
2、加入jniLibs路徑配置,在build.gradle中加入如下配置:
android { …… sourceSets { main { jniLibs.srcDirs = ['libs'] } } }
3、JAVA調(diào)用
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);//調(diào)用 }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() { } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。