ANDROID JNI EXAMPLE GITHUB
Android JNI Example with GitHub Repository
Using Java Native Interface (JNI) in Android allows you to leverage the power of native languages like C and C++ alongside Java, making it possible to interact with system-level libraries and hardware features. If you're looking to get started with JNI in Android, a great way to learn is by looking at practical examples.
In this article, we’ll guide you through setting up a simple JNI example in Android and provide you with a GitHub repository link where you can find the full code to explore and experiment with.
Overview of JNI in Android
JNI enables Java code running on the Android platform to call native C/C++ code, and vice versa. This is particularly useful when you need performance optimizations or when you want to use existing native libraries that provide low-level functionality, like working with hardware sensors or accessing platform-specific features.
The main components for using JNI in Android are:
- Java Code: The Java code that declares the native methods and calls them.
- Native Code: The C or C++ code that implements the logic to be called from Java.
- JNI Bridge: The mechanism that connects the Java code with the native code.
Step-by-Step Example of JNI in Android
Let's go through a simple example where Java code interacts with native C code using JNI. The example will involve a Java method that calls a native C function, which simply returns a message string.
Step 1: Create a New Android Project
- Open Android Studio and create a new Android project.
- Choose an Empty Activity and name your project (e.g.,
JNIDemo).
Step 2: Set Up JNI in Your Android Project
-
Enable C++ support: During project creation, make sure to check the "Include C++ support" checkbox. This will set up your project to work with native code.
-
Create a C++ source file: After creating the project, Android Studio should automatically generate a
cppfolder in theapp/src/main/directory. If not, create it manually.In the
cppfolder, create a new C++ file callednative-lib.cpp.#include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_example_jniproject_MainActivity_stringFromJNI(JNIEnv* env, jobject /* this */) { std::string hello = "Hello from C++"; // Return the string to Java return env->NewStringUTF(hello.c_str()); } -
Create JNI bindings in Java: In your
MainActivity.java, declare the native method that will be implemented in C++.package com.example.jniproject; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Declare the native method public native String stringFromJNI(); // Load the native library static { System.loadLibrary("native-lib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Call the native method and set the text view TextView tv = findViewById(R.id.sample_text); tv.setText(stringFromJNI()); } } -
Update the
CMakeLists.txt: Ensure that yourCMakeLists.txtfile includes the necessary setup to compile the C++ code.cmake_minimum_required(VERSION 3.10.2) project("jniproject") add_library( # Specifies the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). src/main/cpp/native-lib.cpp ) find_library( # Specifies the name of the NDK library that you want to link to. log # Specifies the library path. PATHS ${ANDROID_NDK}/sources/android/cpufeatures ) target_link_libraries( # Specifies the target library. native-lib # Links the target library to the log library # included in the NDK. ${log} )
Step 3: Run the App
Now that the JNI code is integrated:
- Build and run the app on your Android emulator or device.
- You should see the text "Hello from C++" displayed on the screen, which is returned by the native C++ function.
GitHub Repository Example
To make things easier for you, here’s a GitHub repository containing the complete code for this JNI example. You can clone it and run the project on your local machine.
GitHub Repository: Android JNI Example
What’s Inside the GitHub Repo?
In the GitHub repo, you will find the following:
-
Java Code (
MainActivity.java):- The Java class contains the native method declaration and the code to call the native method.
- The native library is loaded via
System.loadLibrary("native-lib"), and the result of the JNI function is set to aTextView.
-
C++ Code (
native-lib.cpp):- This C++ file implements the
stringFromJNIfunction, which returns a simple string to be displayed in the Android app.
- This C++ file implements the
-
CMake Configuration (
CMakeLists.txt):- This file configures the NDK build system, telling it to compile the native C++ code into a shared library called
native-lib.
- This file configures the NDK build system, telling it to compile the native C++ code into a shared library called
-
Android Manifest and Gradle Files:
- These files configure your app to work with the Android build system and ensure everything is set up to work with JNI.
Understanding the Key Components of JNI in Android
To better understand how JNI works in Android, let's break down the key components:
1. Java Native Method Declaration:
In Java, you declare native methods using the native keyword, which indicates that the method will be implemented in native (C/C++) code:
public native String stringFromJNI();
2. Native Code Implementation:
In C/C++, you implement the function that matches the Java native method declaration. The function name is prefixed with Java_ followed by the fully qualified class name and method name, converted to lowercase. The function signature is specified in JNI conventions.
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_jniproject_MainActivity_stringFromJNI(JNIEnv* env, jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
3. CMake Configuration:
CMake is used to build and link the native code. The CMakeLists.txt file specifies which files to compile and which libraries to link to, such as the Android log library:
add_library( native-lib SHARED src/main/cpp/native-lib.cpp )
4. Native Library Loading in Java:
In Java, after defining the native method, you load the native library using System.loadLibrary("native-lib"), where "native-lib" corresponds to the library name defined in the CMake configuration.
static {
System.loadLibrary("native-lib");
}
Conclusion
In this tutorial, we’ve walked through the steps of creating a simple Android app that uses JNI to call a native C++ function. The JNI integration allows us to take advantage of the performance benefits and system-level access that C/C++ provides while working within the Android environment.
For the full example, you can visit the GitHub repository linked above. This example covers the basics of JNI and serves as a great starting point for exploring more advanced JNI features in Android development.
By exploring this example, you can better understand the relationship between Java and native code and how to effectively use JNI in your Android applications.

0 Comments