Invoking Qt/C++ code from the Java side of Qt for android application

We will use JNI for this.
An android app is a standar Java activity which loads the Qt app contained in a .so file.

If we write a java service we may want to access to our Qt/C++ code.

In order to call the C++ code from java we just need:
a. A java class which calls the C++ code
b. the C++ code to execute.

Here are the step to achieve this.

1. Create the java class which will call the C++ code.
Please note that: the class doesn’t load the .so object since it’s already loaded.

package org.gnuton.jni;

public class jniExport {
public native int intMethod(int n);
}

2. Compile the class. Yes we need to perform this action manually!
cd android/org/gnuton/jni
javac jniExport.java

3. create the H file
a. first we move to the dir containg the directories org/gnuton/jni
cd ../../../
b. We run the app which generate our H file
javah org.gnuton.jni.jniExport

The file will look like this:
————————————
/* DO NOT EDIT THIS FILE – it is machine generated */
#include
/* Header for class org_gnuton_jni_jniExport */

#ifndef _Included_org_gnuton_jni_jniExport
#define _Included_org_gnuton_jni_jniExport
#ifdef __cplusplus
extern “C” {
#endif

/*
* Class: org_gnuton_jni_jniExport
* Method: intMethod
* Signature: (I)I

*/

JNIEXPORT jint JNICALL Java_org_gnuton_jni_jniExport_intMethod
(JNIEnv *, jobject, jint);

#ifdef __cplusplus
}

#endif
#endif
————————————

4. create aCpp file like this:
———————————————————————–
#include “jniexport.h”

JNIEXPORT jint JNICALL Java_org_gnuton_jni_jniExport_intMethod(JNIEnv *env, jobject obj, jint num) {

return 17;

}
———————————————————————–

5. We add the java file into the directory: android/org/gnuton/jni of our Qt project and the C++/H file go in the root of our project

6 We add all these files to the project file

7. We can build the code by pressing the “play”/”deploy” button in Qt Creator.