What Is Java Native Interface
What Is Java Native Interface
INTERFACE?
Java Native Interface (JNI) is a neat thing. It allows running Java code from native
applications and libraries written in other languages.
Qt has provided several classes which make using JNI pretty straightforward, amongst which
we will single out QAndroidJniEnvironment and QAndroidJniObject class. This article
will mostly concentrate on how to use the QAndroidJniObject class which provides APIs to
call Java code from C++,which can be very useful if you want to use both Qt
and Android classes for Android development. For example – you define a C++ class which
instantiates a Java class that registers some Android sensors, gathers data from them and
returns it back to the C++ class which can then display that data in a convenient way
using QML.
QT += androidextras
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
DISTFILES += android/AndroidManifest.xml
OTHER_FILES += android/src/com/mycompanyname/myappname/myjavaclass.java
Before I get into details on how to setup the interface, there are a few important points that
have to be covered:
always use fully-qualified class names, such as “java/lang/Class”
method signatures are structured as (A)R, where A is the argument type and R is the return type*
all object types are returned as a QAndroidJniObject
Let’s get started then – to initialize a Java class use the following syntax:
"(Landroid/content/Context;Landroid/app/Activity;)V",
QtAndroid::androidContext().object<jobject>(),
QtAndroid::androidActivity().object<jobject>());
Congratulations, the Java class is now up and running, but what if you want to call a specific
function inside that class? To call a function in Java class that takes no arguments and does
not return anything, use:
m_javaClass.callMethod<void>("javafunctionname");
To call some more complex functions, you need to supply the correct function signature*. It is
important to note that array types in the signature have the ‘[‘ suffix and fully-qualified types
have the ‘L’ prefix and ‘;’ suffix.
For example, to call a function in Java class that takes a string argument and returns an
integer, use:
QAndroidJniEnvironment env;
jclass objectClass = env->GetObjectClass(m_javaClass.object<jobject>());
*Here is a list of tables containing specific JNI types from the official Qt documentation: