Android Call so
The Android virtual machine cannot call the underlying device directly, and we need to use so if we want to call the underlying device.
So use C language or C + + writing complete, using NDK to compile, run directly in the Linux kernel.
By JNI call So when the basic type can be directly interactive, jstring use a bit cumbersome, so I do a jstring and char* to convert the example.
First step:
Create a JNI directory under the engineering root directory. The Libs directory is not built manually.
Note: Use NDK_R7 here so there is no need to use JDK to generate C file headers.
Part II:
Java Authoring Interface file (Device.java)
[Java] view plain copy public class Device {static {system.loadlibrary ("Device"); Public native string deviceteststring (string test); The method name must be declared with the native keyword, and the Class C library must be hosted using System.loadlibrary ("so filename").
Part III:
Preparation of the C document (DEVICES.C)
The C code written here belongs to the Linux C category.
[CPP] View plain copy #include <string.h> #include <jni.h> CHAR*&NBSP;JSTRINGTOSTRM (JNIENV*&NBSP;ENV,&NBSP;JSTRING&NBSP;JSTR) { char* pStr = NULL; jclass jstrObj = (*env)-> Findclass (env, "java/lang/string"); jstring encode = (*env)->newstringutf (env, "Utf-8"); jmethodID methodId = (*env)->getmethodid (env, jstrobj, "getBytes ", " (ljava/lang/string;) [B]; jbyteArray byteArray = ( Jbytearray) (*env)->callobjectmethod (env, jstr, methodid, encode); jsize strlen = (*env)->GetArrayLength (env, bytearray); jbyte *jBuf = (*env)->getbytearrayelements (env, bytearray, jni_false); if (jbuf > 0) { pStr = (char*) malloc (strlen + 1); if (!pstr) { return NULL; } memcpy (Pstr, jbuf, strlen); &Nbsp; pstr[strlen] = 0; } (*env)->releasebytearrayelements (env, bytearray, jbuf, 0); return pStr; } Jstring java_com_jack_device_deviceteststring (Jnienv* env,jclass clazz,jstring path) { //system ("echo devices.so test > /sdcard/log/ Log.txt "); char * test = jstringtostrm (Env,path); return (*env)->newstringutf (env, test); }
Note: C's function naming rules: Java is the JNI standard must have, Com_jack_device is the full name of the Device.java file, and then down is the C function name
The JSTRINGTOSTRM function must be written before the java_com_jack_device_deviceteststring function, if it does not have to be declared at the beginning of the C file.
Declaration Code:
[CPP] view plain copy char* JSTRINGTOSTRM (jnienv* env, jstring jstr); Fourth step: Writing android.mk and compiling
ANDROID.MK files are as follows: