Android: Java and C++ synergy
This is a short checklist how Java and C++ code can synergize and how it is processed. All necessary steps are based on DWG Viewer.
Java: Create a nativ method
C++: Create a matching implementation
Store the C++ implementation inside a shared library
Compile the shared library with CMake
Load the shared library with System.LoadLibrary()
Call the JNI method
Note: When a Java native method is called before the implementation is loaded it leads to a crash!
More details about more complex data transfer can be found in the following topics:
Low level: C++ and JNI data transfer
High level: C++ and JNI data transfer
1. Java: Create a nativ method
JNI.java
public static native void SetBackgroundColor( int color );
2. C++: Create a matching implementation
ARESSimplified_JNI.cpp
JNIEXPORT void JNICALL Java_com_graebert_aressimplified_JNI_SetBackgroundColor( JNIEnv * env, jclass clazz, jint color ){...}
3. Store the C++ implementation inside a shared library
See CFx/AndroidSimplified_JNI/app/CMakeLists.txt
See CFx/CMakeLists.txt
4. Compile the shared library with CMake
Enable CMake compilation inside build.gradle file. Android Studio will take care about the necessary files and compiles everything with the NDK linked to the project.
build.gradle
...externalNativeBuild {
cmake {
arguments "-DANDROID_STL=c++_shared", "-DVIEWER=1"
cppFlags "-std=c++11 -frtti -fexceptions"
}
}
...
externalNativeBuild {
cmake {
path file('../../CMakeLists.txt')
}
}
...
5. Load the shared library with System.LoadLibrary()
To complete the Java and C++ synergy the shared library must be loaded into the host application once before any native method is called.
JNI.java
6. Call the JNI method
Whenever you call a JNI method from the app part of your application, you need to run it from the working thread. The class CFxARESInstance provides the method runOnWorkingThread() for this purpose.
MainActivity.java