Call NDK native functions from Java

16

When writing an Android NDK application you still need to deal with Java code. The simplest way is to subclass NativeActivity with your own class and do things there. Also you may need to call your native C++ functions from that Java class. That could be achieved by the following:

Subclass NativeActivity class:

package com.genius;

public class MyActivity extends NativeActivity
{
    // ...
}

Update the activity name in the manifest:

<activity android:name="com.genius.MyActivity"
    ...
    />

Take a look at your CMakeLists.txt file and find the name of your native library:

add_library(
    myapplib # This one
    SHARED
    ...

Force your native library to be loaded on the app start:

public class MyActivity extends NativeActivity
{
    static
    {
        System.loadLibrary("myapplib");
    }
}

Tell Java about your native function:

public class MyActivity extends NativeActivity
{
    static
    {
        System.loadLibrary("myapplib");
    }

    public native void sayHello(String name);
}

Now, go to your native code. Implement your sayHello function in the following way:

#include <jni.h>

// ...

extern "C"
{

JNIEXPORT void JNICALL Java_com_genius_MyActivity_sayHello(JNIEnv* env, jobject thiz, jstring name)
{
    char const* string = env->GetStringUTFChars(name, 0);
    std::cout << "Hello, " << string << "!\n";
    env->ReleaseStringUTFChars(name, string);
}

}

Your native function name should match the following pattern in order to be found by Java side:

Java_%PACKAGE_NAME%_%CLASS_NAME%_%METHOD_NAME%

Note that you should replace dots with underscores. Also if you use underscores in Java names then you should replace them with _1 sequence. For example: if you package name is com.i_am_genius then your native function should have the following name:

JNIEXPORT void JNICALL Java_com_i_1am_1genius_MyActivity_sayHello(JNIEnv* env, jobject thiz, jstring name)
Share this page:

See also how to:

How to use JNIEnv::FindClass on Android and what you should know about it
How to open URL in web browser from Android NDK application with Java or native code
How to find all Clang arguments that used to build native code in Android Studio
Select target architectures in Android Studio build
The most simple example how to show a message box on Android application