Introduction to Android JNI

Source: Internet
Author: User

Jni api:https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jnitoc.html
The three basic types of jnienv, Jobject and Jclass

The Operation API is in JNIEnv, JNIEnv is the bridge for the Java and C + + communication
Objects passed by the Jobject:java layer (normal native method pass)
class classes corresponding to the Jclass:java layer (static native method pass)

Native common method differs from static method: Jni transfer parameter is jobject and Jclass difference

Android Studio NDK API Auto-Completing
To install the plugin:
Android NDK Support
NDK Workspacemanager Support

Properties, methods, array examples:
Java layer
public class Mainactivity extends Appcompatactivity {

private static final String TAG = "mainactivity";//test Property public String strName = "Test";//Sort array private int[] Array = {89,2,4,3 4,88,100,1};//used to load the ' Native-lib ' library on application startup.static {system.loadlibrary ("Native-lib");}    @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main);    Example of a call to a native method TextView TV = (TextView) Findviewbyid (R.id.sample_text);    Test attribute Operation Tv.settext (UPDATESTRINGFROMC ());    Test method call Tv.settext (Getjavamethod ());    Test array operation This.operatearraysort (array);    for (int i = 0; i < Array.Length; i++) {LOG.E (TAG, "onCreate:" + array[i]);    }//exception handling exception for C + + Java is not a try catch, if the JNI layer has an exception, then Java code call abort try {exception ();    }catch (Exception e) {log.e (TAG, "onCreate:" + e.getmessage ()); } log.e (TAG, "onCreate:" + "End");} Test method public String GetMethod (int a) {return "method" + A;} /** * ANative method that's implemented by the ' native-lib ' native library, * which are packaged with this application. */public native String Stringfromjni ()//returns the string public from C native String Updatestringfromc ();//Call Java method Public native String Getjavamethod ();//The array array is sorted by public native void Operatearraysort (int[] array);//exception handling public native void Exception ();

}

JNI Layer:

#include <jni.h> #include <string> #include "stdlib.h"//c C + + mixed int compare (const void* LHS, const void* RHS) { Return (* (int*) LHS-* (int*) RHS);} Exception handling extern "C" Jniexport void Jnicalljava_com_home_adproj_androidndktest_mainactivity_exception (JNIEnv *env,    Jobject instance) {Jclass _jclass = Env->getobjectclass (instance); Jfieldid _jfieldid = Env->getfieldid (_jclass, "strName2", "ljava/lang/string;"); /strname2 does not exist with exception if (Env->exceptioncheck ()) {//Detect exception Env->exceptionclear ();//clear exception does not cause Java layer to crash//throw exception to Java        Layer Jclass Exceptionclass = Env->findclass ("java/lang/illegalargumentexception"); Env->thrownew (Exceptionclass, "strName2 not Present");//Throw exception to Java layer, Java layer to capture}}//Java array operation extern "C" Jniexport void                                                                  Jnicalljava_com_home_adproj_androidndktest_mainactivity_operatearraysort (jnienv *env, jobject instance, Jintarray array_) {Jint *arrays = env->getintarrayelements (Array_, NULL); int _len = Env->getarraylength (Array_);//Get array length//qsort (void* __base, size_t __nmemb, size_t __size, int (*__compara    Tor) (const void* __LHS, const void* __RHS)); Qsort (Arrays,_len, sizeof (int), compare);//Array sort env->releaseintarrayelements (array_, arrays, 0);//Release}// Call the Java layer method extern "C" Jniexport jstring Jnicalljava_com_home_adproj_androidndktest_mainactivity_getjavamethod (JNIENV    *env, jobject instance) {Jclass _jclass =env->getobjectclass (instance); (Jclass clazz, const char* name, const char* sig) Jmethodid _jmethodid = Env->getmethodid (_jclass, "GetMethod", "(I) ljava/lang/string; ");    /(parameter type) ljava/lang/string return value type jstring result = (jstring) Env->callobjectmethod (instance, _jmethodid,100); char* str = (char *) env->getstringutfchars (result, NULL);//string to char return Env->newstringutf (str);} Test Java Properties operation extern "C" Jniexport jstring JNICALLJAVA_COM_HOME_ADPROJ_ANDROIDNDKTEST_MAINACTIVITY_UPDATESTRINGFROMC (JNIEnv *env, Jobject instance) {//TODO Jclass _jclass = Env->getobjectclass (instance); (Jclass clazz, const char* name, const char* SIG)//name: Attribute name sig: Attribute type Jfieldid _jfieldid = Env->getfieldid (_JC    Lass, "StrName", "ljava/lang/string;");    Jstring _result = (jstring) Env->getobjectfield (instance, _jfieldid);    How to convert to Java string char* str = (char *) env->getstringutfchars (_result, NULL);    Char text[20] = "Success"; Return Env->newstringutf (strcat (Str,text));}        extern "C" Jniexport jstring jnicalljava_com_home_adproj_androidndktest_mainactivity_stringfromjni (JNIEnv* env,    Jobject/* This */) {std::string hello = "Hello from c + +"; Return Env->newstringutf (Hello.c_str ());}

LLDB:JNI Debugging Tools
Official website: http://lldb.llvm.org/tutorial.html

Introduction to Android JNI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.