JNI
Setup in Android using NDK
1. Install NDK
Android Studio → SDK Manager → SDK Tools tab
Enable:
✅ NDK (Side by side)
✅ CMake
✅ LLDB
2. Create new C/C++ source files
To add new C/C++ source files to an existing project, proceed as follows:
If you don't already have a
cpp/directory in the main source set of your app, create one as follows:Open the Project pane on the left side of the IDE and select the Project view from the menu.
Navigate to your-module > src.
Right-click on the main directory and select New > Directory.
Enter cpp as the directory name and click OK.
Right-click the
cpp/directory and select New > C/C++ Source File.Enter a name for your source file, such as
native-lib.From the Type menu, select the file extension for your source file, such as
.cpp.
After you add new C/C++ files to you project, you still need to configure CMake to include the files in your native library.
Edit c++ file:
3. Create a CMake build script
To create a plain text file that you can use as your CMake build script, proceed as follows:
Open the Project pane from the left side of the IDE and select the Project view from the drop-down menu.
Right-click on the root directory of your-module and select New > File.
Enter "CMakeLists.txt" as the filename and click OK.
Add the below code in your CMakeLists.txt:
4. Configure Gradle
To manually configure Gradle to link to your native library, you need to add the externalNativeBuild block to your module-level build.gradle file and configure it with either the cmake or ndkBuild block:
5. Use it in Code
This function call loads the .so file upon application startup.
The native keyword in this method declaration tells the virtual machine that the function is in the shared library (that is, implemented on the native side).