In the recent process of developing Android, I need to call some APIs in the Android terminal through C, and I am an Android program developed in the Java language, so I need to use the JNI call.
The process is to use C to call the Android hardware interface, contract Java to call C's interface, and then encapsulate the code to compile the. so file. Then there is how to introduce and invoke it.
1. Add the. So file to the Libs directory, and the. So file naming convention is lib*,lib followed by a name.
2, join Jnilibs path configuration, add the following configuration in Build.gradle:
Android {... sourcesets {main {jnilibs.srcdirs = [' Libs '}}}
3. Java calls
public class uspjni{ private final static string TAG = "Uspjni"; static { try{ System.loadlibrary ("Uspjni");//Load LIBUSPJNI.SO&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;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&nBsp Uspjni (); } return jni; } public int Uartopen (string path, int flags) &NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;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; } &nBsp; public int uartclose () &NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D ( tag, "(uartclose)"); int Status = this.close (UARTFD); uartfd = -1; if (status != 0) &NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;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]; &NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D (TAG, "(UartRead) len= " + buff.length); return buff; } public int uartflush () { &NBSP;&NBSP;LOG.D (tag, "(Uartflush)"); byte[] data; do { data = uspjni.getinstance (). UartRead (50);//Call }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&NBSP;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 () { }}
This article is from the "Snow July" blog, please be sure to keep this source http://xuepiaoqiyue.blog.51cto.com/4391594/1884139
Java JNI Technology under Android Studio