Android JNI
Definition: JNI is a framework that allows Java code to interact with native code (code written in other languages like C/C++). It's a crucial component for Android development when you need to use native libraries or optimize performance-critical sections of your app.
Purpose:
- Accessing Native Libraries: JNI lets you call functions from native libraries (like PJSIP, SQLite, etc.) directly from your Java/Kotlin code.
- Performance: Native code can be more efficient than Java code for certain tasks, especially when dealing with complex algorithms or low-level operations.
- Hardware Access: You can use JNI to interact directly with hardware components or system APIs.
- Code Reuse: If you have existing C/C++ code, you can reuse it in your Android app via JNI.
- Change the code: You can use JNI to change the code of the library.
- Accessing native libraries: You can use JNI to access native libraries.
Key Concepts in JNI Programming
Native Methods:
- Declaration: In your Java/Kotlin code, you declare native methods using the native keyword. These methods don't have a body in the Java/Kotlin code; their implementation is provided in your native C/C++ code.
1: class MyNativeClass {
2: external fun myNativeFunction(input: String): String
3: // ... other methods
4: }
Implementation::
- In your C/C++ code, you'll implement the corresponding native function. The function name follows a specific naming convention based on the Java method name.
1: extern "C" jstring
2: Java_com_example_ndk_MainActivity_stringFromJNI( JNIEnv* env, jobject thiz)
3: {
4: return (*env)->NewStringUTF(env, "Hello from JNI !");
5: }
JNIEnv (JNI Environment):
- Interface: JNIEnv is a pointer to a structure that represents the JNI environment. It provides a set of functions for interacting with the Java Virtual Machine (JVM).
- Accessing Java Objects: You use JNIEnv to create, access, and manipulate Java objects from your native code.
- Calling Java Methods: You can use JNIEnv to call Java methods from your native code.
- Exception Handling: JNIEnv allows you to handle exceptions thrown by Java code.
- JNIEnv: JNIEnv is a pointer to a structure that represents the JNI environment.
AndroidJavaLearning context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/AndroidConcept/Index10.htm
|
|