A Guide to Adding JNI to Your Android App
- published
- reading time
- 2 minutes
Introduction
Java Native Interface (JNI) is a framework that allows Java code running in the Java Virtual Machine (JVM) to call and be called by native applications and libraries written in other languages such as C and C++. This can be incredibly useful in Android development when you need to incorporate native code for performance optimization or to utilize existing libraries. In this guide, we’ll walk through the steps to add JNI to your Android app.
What is JNI?
- JNI is a framework that enables Java code running in the JVM to interact with native code written in languages like C or C++.
- It provides a way to access native features and libraries that might not be available in Java.
- JNI is often used for tasks requiring low-level hardware interactions, such as accessing sensors or implementing performance-critical algorithms.
This guide is written with Kali Linux 2024.1 in mind, but the steps outlined here are applicable to other Linux distributions as well.
Steps to Add JNI to Your Android App
I’m utilizing the Pixel XL API 24 emulator for this guide.
I have android-studio installed at /home/kali/android-studio/
. To start it use the following command:
$ /home/kali/android-studio/bin/studio.sh
Step 1: Set Up Your Android Project
- Open Android Studio and create a new Android project or open an existing one.
- Make sure you have the necessary SDKs and build tools installed for your project.
Step 2: Create Your JNI Folder Structure
- Inside your Android project, create a new folder to hold your JNI code. Conventionally, this folder is named jni or src/main/jni.
Alternatively, you have the option to manually navigate to your project directory and create the jni directory yourself.
In my situation, my Android Studio projects are located at /home/kali/AndroidStudioProjects/, and specifically, this JNI_App project is at /home/kali/AndroidStudioProjects/JNI_App/.
$ cd /home/kali/AndroidStudioProjects/JNI_App/
$ cd app/src/main/
$ mkdir jni
$ ls
AndroidManifest.xml java jni res
- Within the jni folder, create a C source file (e.g., native-lib.c). This file will contain the native C code you want to call from your Java/Kotlin code.
To do this follow the following steps:
- Next, in the jni directory, right-click and choose New -> CMakeLists.txt. Also, select New -> C/C++ Source File -> {Name -> native-lib & Type -> C}.
Step 3: Write Your Native C Code
- Open the native-lib.c file you created.
- Write your native C functions. For example: