SlideShare une entreprise Scribd logo
1  sur  33
Android JNI/NDK
Android JNI
● Why JNI?
● What is NDK?
● Why NDK?
● Deep into JNI world.
Why JNI?
Android is put together of about equal part Java and C.
we need an easy way to bridge between these two totally different worlds
.Java offers Java Native Interface
(JNI) as a framework connecting the world of Java to the native code.
More About JNI
JNI is part of Dalvik VM, which allows native code to access java
environment. Like accessing java objects and its methods, members etc.
JNI also facilitates accessing and invoking of native methods from Java
code.
JNI Comes with Primitive and reference types.
Primitive types can be manipulated directly as these are equivalent to native
c.c++ data types
But you need special helper functions to manipulate JNI reference types.
What is NDK?
NDK is a toolchain
Cross-compiler, linker, what you need to build for ARM, x86, MIPS, etc.
NDK provides a way to bundle lib.so into your APK
The native library needs to be loadable in a secure way.
NDK "standardizes" various native platforms
It provides headers for libc, libm, libz, lliibblloogg, lliibbjjnniiggrraahhiiccss,
OpenGL/OpenSL ES,
JNI headers, minimal C++ support headers, and Android native app APIs
NDK in Action
Why NDK/JNI?
For performance
Sometimes, native code still runs faster.
For legacy support
You may have that C/C++ code you’d like to use in your app.
For access to low-level libraries
I n a rare case when there is no Java API to do something.
For cross-platform development
But Adding JNI to your app will make it more complex.
Build Process
Deep Into JNI world
Loading Native Libraries and
Registering Native Methods
Native code is usually compiled into a shared library and loaded before the
native methods can be called.
All the Native methods are declared with native keyword in java.
static {
//use either of the two methods below
System.loadLibrary(“nativelib");
System.load("/data/data/cookbook.chapter2/lib/ libNative.so");
}
Registering Native Methods
 JNIEnv Interface Pointer:
Every native method defined in native code at JNI must accept two input
parameters, the first one being a pointer to JNIEnv. The JNIEnv interface pointer is
pointing to thread-local data, which in turn points to a JNI function table shared by
all threads. This can be illustrated using the following diagram:
JNIEnv
Gateway to access all predefined JNI functions.
Access Java Fields
Invoke Java Methods.
It points to the thread’s local data, so it cannot be shared.
It can be accessible only by java threads.
Native threads must call AttachCurrentThread to attach itself to VM and to
obtain the JNIEnv interface pointer.
RegisterNatives :
 Two ways:
 1. Using Javah tool.
 2. Using RegisterNative function.
Using RegisterNative Method
Prototype:
jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod
*methods, jint nMethods);
The clazz argument is a reference to the class in which the native method is
to be registered. The methods argument is an array of the JNINativeMethod
data structure.
JNINativeMethod is defined as follows:
typedef struct {
char *name;
char *signature;
void *fnPtr;
} JNINativeMethod;
name indicates the native method name, signature is the descriptor of the
method's input argument data type and return value data type, and fnPtr is the
function pointer pointing to the native method.
The last argument, nMethods of RegisterNatives, indicates the number of
methods to register. The function returns zero to indicate success, and a
negative value otherwise.
JNI_OnLoad
 Invoke when the native library is loaded.
 It is the right and safe place to register the native methods before their
execution.
 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved)
 {
 JNIEnv* env;
 if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6)) {
 return -1;
 }
 // Get jclass with env->FindClass.
 // Register methods with env->RegisterNatives.
 return JNI_VERSION_1_6;
 }
JNI Datatypes
Manipulating strings in JNI
 Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally
different.
 Java programming language uses UTF-16 to represent strings. If a character cannot fit in a 16-bit code
value, a pair of code values named surrogate pair is used
 C strings are simply an array of bytes terminated by a null character
 The Unicode Standard is a character coding system designed to support the
worldwide interchange, processing, and display of the written texts of the
diverse languages and technical disciplines of the modern world. In addition, it
supports classical and historical texts of many written languages.
 Few JNI String Functions:
 jstring NewStringUTF(JNIEnv *env, const char *bytes);
 void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char
*buf);
 void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);
 const jbyte * GetStringUTFChars(JNIEnv *env, jstring string, jboolean
*isCopy);
Manipulating Objects in JNI
jobject AllocObject(JNIEnv *env, jclass clazz);
jobject NewObject(JNIEnv *env, jclass clazz,jmethodID
methodID, ...);
jobject NewObjectA(JNIEnv *env, jclass clazz,jmethodID
methodID, jvalue *args);
jobject NewObjectV(JNIEnv *env, jclass clazz,jmethodID
methodID, va_list args);
 The clazz argument is a reference to the Java class of which we want to create
an instance object. It cannot be an array class, which has its own set of JNI
functions.
 methodID is the constructor method ID, which can be obtained using the
GetMethodID JNI function.
Manipulating Classes in JNI
jclass FindClass(JNIEnv *env, const char *name);
 Majorly used method when writing JNI code.
 Must pass full path of class.
 If you have to call this method for finding the most used class in JNI, it is
better to Cache it.
Accessing Java Static and Instance
fileds in Native code
 jfieldID data type: jfieldID is a regular C pointer pointing to a data structure
with details hidden from developers. We should not confuse it with jobject or
its subtypes. jobject is a reference type corresponding to Object in Java,
while jfieldID doesn't have such a corresponding type in Java. However, JNI
provides functions to convert the java.lang.reflect.Field instance to jfieldID
and vice versa.
 Field descriptor: It refers to the modified UTF-8 string used to represent the
field data type. The following table summarizes the Java field types and its
corresponding field descriptors:
Accessing static fields
 JNI provides three functions to access static fields of a Java class. They
have the following prototypes:
jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);
<NativeType> GetStatic<Type>Field(JNIEnv
*env,jclass clazz, jfieldID fieldID);
void SetStatic<Type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID,<NativeType> value);
Accessing instance field
 Accessing instance fields is similar to accessing static fields. JNI also
provides the following three functions for us:
jfieldID GetFieldID(JNIEnv *env, jclass clazz, const
char *name, const char *sig);
<NativeType> Get<Type>Field(JNIEnv *env,jobject
obj, jfieldID fieldID);
void Set<Type>Field(JNIEnv *env, jobject obj, jfieldID
fieldID, <NativeType> value);
Calling static and instance methods
from the native code
 jmethodID data type: Similar to jfieldID, jmethodID is a regular C pointer
pointing to a data structure with details hidden from the developers. JNI
provides functions to convert the java.lang.reflect.Method instance to
jmethodID and vice versa.
 Method descriptor: This is a modified UTF-8 string used to represent the
input (input arguments) data types and output (return type) data type of the
method. Method descriptors are formed by grouping all field descriptors of its
input arguments inside a "()", and appending the field descriptor of the return
type. If the return type is void, we should use "V". If there's no input
arguments, we should simply use "()", followed by the field descriptor of the
return type. For constructors, "V" should be used to represent the return
type. The following table lists a few Java methods and their corresponding
method descriptors:
Calling static methods:
 JNI provides four sets of functions for native code to call Java methods.
Their prototypes are as follows:
jmethodID GetStaticMethodID(JNIEnv *env, jclass
clazz, const char *name, const char *sig);
<NativeType> CallStatic<Type>Method(JNIEnv *env,
jclass clazz, jmethodID methodID, ...);
<NativeType> CallStatic<Type>MethodA(JNIEnv
*env, jclass clazz, jmethodID methodID, jvalue *args);
<NativeType> CallStatic<Type>MethodV(JNIEnv
*env, jclass clazz,jmethodID methodID, va_list args);
Calling instance methods:
 Calling instance methods from the native code is similar to calling static methods.
JNI also provides four sets of functions as follows:
jmethodID GetMethodID(JNIEnv *env, jclass clazz, const
char *name, const char *sig);
<NativeType> Call<Type>Method(JNIEnv *env, jobject obj,
jmethodID methodID, ...);
<NativeType> Call<Type>MethodA(JNIEnv *env,jobject
obj, jmethodID methodID, jvalue *args);
<NativeType> Call<Type>MethodV(JNIEnv *env, jobject
obj, jmethodID methodID, va_list args);
Checking errors and handling
exceptions in JNI
 JNI functions can fail because of system constraint (for example, lack of
memory) or invalid arguments (for example, passing a native UTF-8 string
when the function is expecting a UTF-16 string).
 Check for errors and exceptions: Many JNI functions return a special value
to indicate failure. For example, the FindClass function returns NULL to
indicate it failed to load the class. Many other functions do not use the return
value to signal failure; instead an exception is thrown.
 jboolean ExceptionCheck(JNIEnv *env);
 jthrowable ExceptionOccurred(JNIEnv *env);
 void ExceptionDescribe(JNIEnv *env);
Throw exceptions in the native
code:
 JNI provides two functions to throw an exception from native code. They
have the following prototypes:
jint Throw(JNIEnv *env, jthrowable obj);
jint ThrowNew(JNIEnv *env, jclass clazz, const char
*message);
 The first function accepts a reference to a jthrowable object and throws the
exception, while the second function accepts a reference to an exception
class. It will create an exception object of the clazz class with the message
argument and throw it.
Extended Error Check
 Using CheckJNI

Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv
function table pointers are switched to tables of functions that perform an
extended series of checks before calling the standard implementation.
 List of Errors that CheckJNI tool can catch:
 Arrays: attempting to allocate a negative-sized array.
 Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL
pointer to a JNI call with a non-nullable argument.
 Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
 Critical calls: making a JNI call between a “critical” get and its corresponding release.
 Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
 Exceptions: making a JNI call while there’s an exception pending.
 JNIEnv*s: using a JNIEnv* from the wrong thread.
 jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong
type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static
field to set an instance field or vice versa, or using a jfieldID from one class with instances
of another class.
Enabling CheckJNI
 Enable CheckJNI:
 For Production Builds
 adb shell setprop debug.checkjni 1
 For Engineering Builds:
 adb shell stop
 adb shell setprop dalvik.vm.checkjni true
 adb shell start
Memory Issues
 Using Libc Debug Mode
 adb shell setprop libc.debug.malloc 1
 adb shell stop
 adb shell start
 Supported libc debug mode values are
 1: Perform leak detection.
 5: Fill allocated memory to detect overruns.
 10: Fill memory and add sentinel to detect overruns.
Further Reading
 Native Threads usage
 More about references
 JNI Graphics using OpenGL
 Audio using OpenSL apis.
 http://developer.android.com/training/articles/perf-jni.html
Questions??

Contenu connexe

Tendances

The Android graphics path, in depth
The Android graphics path, in depthThe Android graphics path, in depth
The Android graphics path, in depthChris Simmonds
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Opersys inc.
 
Accessing Hardware on Android
Accessing Hardware on AndroidAccessing Hardware on Android
Accessing Hardware on AndroidGary Bisson
 
Android HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacyAndroid HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacyJollen Chen
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps DevelopmentProf. Erwin Globio
 
Understanding the Android System Server
Understanding the Android System ServerUnderstanding the Android System Server
Understanding the Android System ServerOpersys inc.
 
U-Boot presentation 2013
U-Boot presentation  2013U-Boot presentation  2013
U-Boot presentation 2013Wave Digitech
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesChris Simmonds
 

Tendances (20)

The Android graphics path, in depth
The Android graphics path, in depthThe Android graphics path, in depth
The Android graphics path, in depth
 
Embedded Android : System Development - Part II (HAL)
Embedded Android : System Development - Part II (HAL)Embedded Android : System Development - Part II (HAL)
Embedded Android : System Development - Part II (HAL)
 
Android IPC Mechanism
Android IPC MechanismAndroid IPC Mechanism
Android IPC Mechanism
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Introduction to Android Window System
Introduction to Android Window SystemIntroduction to Android Window System
Introduction to Android Window System
 
Accessing Hardware on Android
Accessing Hardware on AndroidAccessing Hardware on Android
Accessing Hardware on Android
 
Android HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacyAndroid HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacy
 
Embedded Android : System Development - Part I
Embedded Android : System Development - Part IEmbedded Android : System Development - Part I
Embedded Android : System Development - Part I
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps Development
 
Understanding the Android System Server
Understanding the Android System ServerUnderstanding the Android System Server
Understanding the Android System Server
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
Aidl service
Aidl serviceAidl service
Aidl service
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Android internals
Android internalsAndroid internals
Android internals
 
U-Boot presentation 2013
U-Boot presentation  2013U-Boot presentation  2013
U-Boot presentation 2013
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot images
 

En vedette

Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolGabor Paller
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VMYongqiang Li
 
Let's talk about jni
Let's talk about jniLet's talk about jni
Let's talk about jniYongqiang Li
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeAlain Leon
 
Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Doug Hawkins
 
Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)Egor Elizarov
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)Niraj Solanke
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineChun-Yu Wang
 

En vedette (10)

Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
Dancing with dalvik
Dancing with dalvikDancing with dalvik
Dancing with dalvik
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VM
 
Let's talk about jni
Let's talk about jniLet's talk about jni
Let's talk about jni
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik Bytecode
 
Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011
 
Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 

Similaire à Android JNI

Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNIKirill Kounik
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)DroidConTLV
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worthIdan Sheinberg
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)Ron Munitz
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jniPeter Hagemeyer
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)Ron Munitz
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDKBeMyApp
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slidesunny khan
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Paris Android User Group
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++Joan Puig Sanz
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Nuzhat Memon
 

Similaire à Android JNI (20)

Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Android and cpp
Android and cppAndroid and cpp
Android and cpp
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Developing android apps with java 8
Developing android apps with java 8Developing android apps with java 8
Developing android apps with java 8
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
 

Dernier

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Android JNI

  • 2. Android JNI ● Why JNI? ● What is NDK? ● Why NDK? ● Deep into JNI world.
  • 3. Why JNI? Android is put together of about equal part Java and C. we need an easy way to bridge between these two totally different worlds .Java offers Java Native Interface (JNI) as a framework connecting the world of Java to the native code.
  • 4. More About JNI JNI is part of Dalvik VM, which allows native code to access java environment. Like accessing java objects and its methods, members etc. JNI also facilitates accessing and invoking of native methods from Java code. JNI Comes with Primitive and reference types. Primitive types can be manipulated directly as these are equivalent to native c.c++ data types But you need special helper functions to manipulate JNI reference types.
  • 5. What is NDK? NDK is a toolchain Cross-compiler, linker, what you need to build for ARM, x86, MIPS, etc. NDK provides a way to bundle lib.so into your APK The native library needs to be loadable in a secure way. NDK "standardizes" various native platforms It provides headers for libc, libm, libz, lliibblloogg, lliibbjjnniiggrraahhiiccss, OpenGL/OpenSL ES, JNI headers, minimal C++ support headers, and Android native app APIs
  • 7. Why NDK/JNI? For performance Sometimes, native code still runs faster. For legacy support You may have that C/C++ code you’d like to use in your app. For access to low-level libraries I n a rare case when there is no Java API to do something. For cross-platform development But Adding JNI to your app will make it more complex.
  • 10. Loading Native Libraries and Registering Native Methods Native code is usually compiled into a shared library and loaded before the native methods can be called. All the Native methods are declared with native keyword in java. static { //use either of the two methods below System.loadLibrary(“nativelib"); System.load("/data/data/cookbook.chapter2/lib/ libNative.so"); }
  • 11. Registering Native Methods  JNIEnv Interface Pointer: Every native method defined in native code at JNI must accept two input parameters, the first one being a pointer to JNIEnv. The JNIEnv interface pointer is pointing to thread-local data, which in turn points to a JNI function table shared by all threads. This can be illustrated using the following diagram:
  • 12. JNIEnv Gateway to access all predefined JNI functions. Access Java Fields Invoke Java Methods. It points to the thread’s local data, so it cannot be shared. It can be accessible only by java threads. Native threads must call AttachCurrentThread to attach itself to VM and to obtain the JNIEnv interface pointer. RegisterNatives :  Two ways:  1. Using Javah tool.  2. Using RegisterNative function.
  • 13. Using RegisterNative Method Prototype: jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint nMethods); The clazz argument is a reference to the class in which the native method is to be registered. The methods argument is an array of the JNINativeMethod data structure. JNINativeMethod is defined as follows: typedef struct { char *name; char *signature; void *fnPtr; } JNINativeMethod; name indicates the native method name, signature is the descriptor of the method's input argument data type and return value data type, and fnPtr is the function pointer pointing to the native method. The last argument, nMethods of RegisterNatives, indicates the number of methods to register. The function returns zero to indicate success, and a negative value otherwise.
  • 14. JNI_OnLoad  Invoke when the native library is loaded.  It is the right and safe place to register the native methods before their execution.  JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved)  {  JNIEnv* env;  if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6)) {  return -1;  }  // Get jclass with env->FindClass.  // Register methods with env->RegisterNatives.  return JNI_VERSION_1_6;  }
  • 16. Manipulating strings in JNI  Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally different.  Java programming language uses UTF-16 to represent strings. If a character cannot fit in a 16-bit code value, a pair of code values named surrogate pair is used  C strings are simply an array of bytes terminated by a null character  The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages and technical disciplines of the modern world. In addition, it supports classical and historical texts of many written languages.  Few JNI String Functions:  jstring NewStringUTF(JNIEnv *env, const char *bytes);  void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);  void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);  const jbyte * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);
  • 17. Manipulating Objects in JNI jobject AllocObject(JNIEnv *env, jclass clazz); jobject NewObject(JNIEnv *env, jclass clazz,jmethodID methodID, ...); jobject NewObjectA(JNIEnv *env, jclass clazz,jmethodID methodID, jvalue *args); jobject NewObjectV(JNIEnv *env, jclass clazz,jmethodID methodID, va_list args);  The clazz argument is a reference to the Java class of which we want to create an instance object. It cannot be an array class, which has its own set of JNI functions.  methodID is the constructor method ID, which can be obtained using the GetMethodID JNI function.
  • 18. Manipulating Classes in JNI jclass FindClass(JNIEnv *env, const char *name);  Majorly used method when writing JNI code.  Must pass full path of class.  If you have to call this method for finding the most used class in JNI, it is better to Cache it.
  • 19. Accessing Java Static and Instance fileds in Native code  jfieldID data type: jfieldID is a regular C pointer pointing to a data structure with details hidden from developers. We should not confuse it with jobject or its subtypes. jobject is a reference type corresponding to Object in Java, while jfieldID doesn't have such a corresponding type in Java. However, JNI provides functions to convert the java.lang.reflect.Field instance to jfieldID and vice versa.  Field descriptor: It refers to the modified UTF-8 string used to represent the field data type. The following table summarizes the Java field types and its corresponding field descriptors:
  • 20.
  • 21. Accessing static fields  JNI provides three functions to access static fields of a Java class. They have the following prototypes: jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> GetStatic<Type>Field(JNIEnv *env,jclass clazz, jfieldID fieldID); void SetStatic<Type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID,<NativeType> value);
  • 22. Accessing instance field  Accessing instance fields is similar to accessing static fields. JNI also provides the following three functions for us: jfieldID GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> Get<Type>Field(JNIEnv *env,jobject obj, jfieldID fieldID); void Set<Type>Field(JNIEnv *env, jobject obj, jfieldID fieldID, <NativeType> value);
  • 23. Calling static and instance methods from the native code  jmethodID data type: Similar to jfieldID, jmethodID is a regular C pointer pointing to a data structure with details hidden from the developers. JNI provides functions to convert the java.lang.reflect.Method instance to jmethodID and vice versa.  Method descriptor: This is a modified UTF-8 string used to represent the input (input arguments) data types and output (return type) data type of the method. Method descriptors are formed by grouping all field descriptors of its input arguments inside a "()", and appending the field descriptor of the return type. If the return type is void, we should use "V". If there's no input arguments, we should simply use "()", followed by the field descriptor of the return type. For constructors, "V" should be used to represent the return type. The following table lists a few Java methods and their corresponding method descriptors:
  • 24.
  • 25. Calling static methods:  JNI provides four sets of functions for native code to call Java methods. Their prototypes are as follows: jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> CallStatic<Type>Method(JNIEnv *env, jclass clazz, jmethodID methodID, ...); <NativeType> CallStatic<Type>MethodA(JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args); <NativeType> CallStatic<Type>MethodV(JNIEnv *env, jclass clazz,jmethodID methodID, va_list args);
  • 26. Calling instance methods:  Calling instance methods from the native code is similar to calling static methods. JNI also provides four sets of functions as follows: jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> Call<Type>Method(JNIEnv *env, jobject obj, jmethodID methodID, ...); <NativeType> Call<Type>MethodA(JNIEnv *env,jobject obj, jmethodID methodID, jvalue *args); <NativeType> Call<Type>MethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
  • 27. Checking errors and handling exceptions in JNI  JNI functions can fail because of system constraint (for example, lack of memory) or invalid arguments (for example, passing a native UTF-8 string when the function is expecting a UTF-16 string).  Check for errors and exceptions: Many JNI functions return a special value to indicate failure. For example, the FindClass function returns NULL to indicate it failed to load the class. Many other functions do not use the return value to signal failure; instead an exception is thrown.  jboolean ExceptionCheck(JNIEnv *env);  jthrowable ExceptionOccurred(JNIEnv *env);  void ExceptionDescribe(JNIEnv *env);
  • 28. Throw exceptions in the native code:  JNI provides two functions to throw an exception from native code. They have the following prototypes: jint Throw(JNIEnv *env, jthrowable obj); jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);  The first function accepts a reference to a jthrowable object and throws the exception, while the second function accepts a reference to an exception class. It will create an exception object of the clazz class with the message argument and throw it.
  • 29. Extended Error Check  Using CheckJNI  Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.  List of Errors that CheckJNI tool can catch:  Arrays: attempting to allocate a negative-sized array.  Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.  Class names: passing anything but the “java/lang/String” style of class name to a JNI call.  Critical calls: making a JNI call between a “critical” get and its corresponding release.  Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.  Exceptions: making a JNI call while there’s an exception pending.  JNIEnv*s: using a JNIEnv* from the wrong thread.  jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
  • 30. Enabling CheckJNI  Enable CheckJNI:  For Production Builds  adb shell setprop debug.checkjni 1  For Engineering Builds:  adb shell stop  adb shell setprop dalvik.vm.checkjni true  adb shell start
  • 31. Memory Issues  Using Libc Debug Mode  adb shell setprop libc.debug.malloc 1  adb shell stop  adb shell start  Supported libc debug mode values are  1: Perform leak detection.  5: Fill allocated memory to detect overruns.  10: Fill memory and add sentinel to detect overruns.
  • 32. Further Reading  Native Threads usage  More about references  JNI Graphics using OpenGL  Audio using OpenSL apis.  http://developer.android.com/training/articles/perf-jni.html