Defines a way for bytecode (Compiled from Java or Kotlin) to interact with native code (written in C/C++).

Use cases for native code on Android

Java Native Interface Specification Contents

Untitled

One of the most important parameters in native functions is JNIEnv(Java Interface Environment) pointer. This pointer refer to array of other pointers that they are helper function for native code to interact with Android API.

Untitled

How to call native methods from Java

You call the native methods in Java, we need to fist register native methods to be accessible by Java. There are two methods to do this job.

  1. Runtime Discovery

    1. Exported native methods must be appropriately named, i.e. Java_your_class_path_methodName (e.g. Java_lab_seczone64_MainActivity_stringFromJNI)
  2. Explicitly register your exported methods using RegisterNatives function.

    // Find your class. JNI_OnLoad is called from the correct class loader context for this to work.
    jclass c = env->FindClass("com/example/app/package/MyClass");
    if (c == nullptr) return JNI_ERR;
    
    // Register your class' native methods.
    static const JNINativeMethod methods[] = {
        {"nativeFoo", "()V", reinterpret_cast<void*>(nativeFoo)},
        {"nativeBar", "(Ljava/lang/String;I)Z", reinterpret_cast<void*>(nativeBar)},
    };
    int rc = env->RegisterNatives(c, methods, sizeof(methods)/sizeof(JNINativeMethod));
    

Now where we should place this code?