Android JNI example

This example shows how to use JNI (Java Native Interface) to call C functions from Java and the other way around. Note that, the application fully functions only on Android.

You can find the example in <KanziWorkspace>/Examples/Android_JNI.

To build and install this example for Android:

  1. Open the Kanzi Command Prompt (it sets all the necessary environment variables)
  2. Go to <KanziWorkspace>/Examples/Android_JNI/Application/configs/platforms/android
  3. Run scons es2 debug AndroidJNI
  4. Run adb install ..\..\..\output\AndroidJNIExample-debug.apk

Part of the logic in the example application is in Android Activity defined in Application\configs\platforms\android\src\com\rightware\kanzi\AndroidJNIExample\AndroidJNIExample.java

In the activity we setup a timer which updates the Kanzi UI periodically using the JNI interface method called updateKanziViewport. To declare JNI interface methods, you have to add native keyword before the function.

This example also declares getRPMValue, which when called from the C code, gets the RPM value.

You can find the rest of the application logic in the <KanziWorkspace>/Examples/Android_JNI/Application/src/android_jni.c. Take a look at the header file first. The JNI interface function updateKanziViewport is declared in the following way:

JNIEXPORT void JNICALL
Java_com_rightware_kanzi_AndroidJNIExample_AndroidJNIExample_updateKanziViewport(JNIEnv* env, jobject obj, jfloat needlePosition, jstring throttle);

The function name consists of a Java keyword, the package name, the class name and the function name. In addition to the function parameters, the function takes the JNI environment and a Java object as parameters.

In the android_jni.c file you can see the function definition. There you can find an example of how you can convert the jstring object to Kanzi mutable string.

To call a Java method use function getRPMValueFromJava. See the definition. To simplify the process, the example contains a few macros, you can use. To call a Java method, get a handle to the JNI environment and then ask for method by name and signature. In this example, query the getRPMValue method without any parameters and a integer return type.

For more information about the JNI, see http://developer.android.com/guide/practices/design/jni.html.

See also

Deploying Kanzi applications to Android