SlideShare a Scribd company logo
Using the Android* Native Development Kit (NDK) 
Alexander Weggerle, Technical Consultant Engineer, Intel Corporation
2 
1 in 1,374,589 
2
3 
Agenda 
• The Android* Native Development Kit (NDK) 
• Developing an application that uses the NDK 
• Supporting several CPU architectures 
• Debug and Optimization 
• Some more tips 
• Q&A
4 
Android* Native Development Kit (NDK) 
What is it? 
 Build scripts/toolkit to incorporate native code in Android* apps via the Java Native 
Interface (JNI) 
Why use it? 
 Performance 
 e.g., complex algorithms, multimedia applications, games 
 Differentiation 
 app that takes advantage of direct CPU/HW access 
 e.g., using SSSE3 for optimization 
 Fluid and lag-free animations 
 Software code reuse 
Why not use it? 
 Performance improvement isn’t always 
guaranteed, in contrary to the added 
complexity
5 
NDK Application Development 
C/C++ 
Code 
Makefile 
ndk-build 
Mix with 
Java* 
GDB 
debug 
SDK APIs 
Java Framework 
Using JNI 
JNI 
Native Libs 
Android* Application 
NDK APIs 
Bionic C Library
6 
Compatibility with Standard C/C++ 
Bionic C Library: 
 Lighter than standard GNU C Library 
 Not POSIX compliant 
 pthread support included, but limited 
 No System-V IPCs 
 Access to Android* system properties 
Bionic is not binary-compatible with the standard C library 
It means you generally need to (re)compile everything using the Android NDK toolchain
7 
Android* C++ Support 
By default, system is used. It lacks: 
 Standard C++ Library support (except some headers) 
 C++ exceptions support 
 RTTI support 
Fortunately, you have other libs available with the NDK: 
Runtime Exceptions RTTI STL 
system No No No 
gabi++ Yes Yes No 
stlport Yes Yes Yes 
gnustl Yes Yes Yes 
libc++ Yes Yes Yes 
Choose which library to compile 
against in your Makefile 
(Application.mk file): 
APP_STL := gnustl_shared 
Postfix the runtime with _static 
or _shared 
For using C++ features, you also need to enable these in your Makefile: 
LOCAL_CPP_FEATURES += exceptions rtti
8 
Installing the Android* NDK 
NDK is a platform dependent archive: 
It provides: 
PSI 
TS 
PIDs 
 A build environment 
 Android* headers and libraries 
 Documentation and samples 
(these are very useful) 
You can integrate it with Eclipse ADT:
9 
Manually Adding Native Code to an Android* Project 
Standard Android* Project Structure 
Native Sources - JNI Folder 
1. Create JNI folder for 
native sources 
3. Create Android.mk 
Makefile 
2. Reuse or create native 
4. Build Native libraries using NDK-BUILD 
script. 
c/c++ sources 
NDK-BUILD will automatically 
create ABI libs folders.
10 
Adding NDK Support to your Eclipse Android* 
Project
11 
Android* NDK Samples 
Sample App Type 
hello-jni Call a native function written in C from Java*. 
bitmap-plasma Access an Android* Bitmap object from C. 
san-angeles EGL and OpenGL* ES code in C. 
hello-gl2 EGL setup in Java and OpenGL ES code in C. 
native-activity 
C only OpenGL sample 
(no Java, uses the NativeActivity class). 
two-libs Integrates more than one library 
…
12 
Focus on Native Activity 
Only native code in the project 
android_main() entry point running in its own thread 
Event loop to get input data and frame drawing messages 
/** 
* This is the main entry point of a native application that is using 
* android_native_app_glue. It runs in its own thread, with its own 
* event loop for receiving input events and doing other things. 
*/ 
void android_main(struct android_app* state);
13 
Integrating Native Functions with Java* 
Declare native methods in your Android* application (Java*) using the ‘native’ keyword: 
public native String stringFromJNI(); 
PSI 
TS 
PIDs 
Provide a native shared library built with the NDK that contains the methods used by your application: 
libMyLib.so 
Your application must load the shared library (before use… during class load for example): 
static { 
System.loadLibrary("MyLib"); 
} 
There is two ways to associate your native code to the Java methods: javah and JNI_OnLoad
14 
Javah Method 
“javah” helps automatically generate the appropriate JNI header stubs based on 
the Java* source files from the compiled Java classes files: 
Example: 
> javah –d jni –classpath bin/classes  
com.example.hellojni.HelloJni 
Generates com_example_hellojni_HelloJni.h file with this definition: 
JNIEXPORT jstring JNICALL 
Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv *, jobject);
15 
Javah Method 
C function that will be automatically mapped: 
jstring 
Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env, 
jobject thiz ) 
{ 
return (*env)->NewStringUTF(env, "Hello from JNI !"); 
} 
... 
{ 
... 
tv.setText( stringFromJNI() ); 
... 
} 
public native String stringFromJNI(); 
static { 
System.loadLibrary("hello-jni"); 
}
19 
Memory Handling of Java* Objects 
Memory handling of Java* objects is done by the JVM: 
• You only deal with references to these objects 
• Each time you get a reference, you must not forget to delete it 
after use 
• local references are automatically deleted when the native call 
returns to Java 
• References are local by default 
• Global references are only created by NewGlobalRef()
20 
Creating a Java* String 
C: 
jstring string = 
(*env)->NewStringUTF(env, "new Java String"); 
C++: 
jstring string = env->NewStringUTF("new Java String"); 
Memory is handled by the JVM, jstring is always a reference. 
You can call DeleteLocalRef() on it once you finished with it. 
Main difference with compiling JNI code in C or in C++ is the nature of “env” as you can 
see it here. 
Remember that otherwise, the API is the same.
21 
Getting a C/C++ String from Java* String 
const char *nativeString = (*env)- 
>GetStringUTFChars(javaString, null); 
… 
(*env)->ReleaseStringUTFChars(env, javaString, nativeString); 
//more secure 
int tmpjstrlen = env->GetStringUTFLength(tmpjstr); 
char* fname = new char[tmpjstrlen + 1]; 
env->GetStringUTFRegion(tmpjstr, 0, tmpjstrlen, fname); 
fname[tmpjstrlen] = 0; 
… 
delete fname;
22 
Handling Java* Exceptions 
// call to java methods may throw Java exceptions 
jthrowable ex = (*env)->ExceptionOccurred(env); 
if (ex!=NULL) { 
(*env)->ExceptionClear(env); 
// deal with exception 
} 
(*env)->DeleteLocalRef(env, ex);
24 
Calling Java* Methods 
On an object instance: 
jclass clazz = (*env)->GetObjectClass(env, obj); 
jmethodID mid = (*env)->GetMethodID(env, clazz, "methodName", 
"(…)…"); 
if (mid != NULL) 
(*env)->Call<Type>Method(env, obj, mid, parameters…); 
Static call: 
jclass clazz = (*env)->FindClass(env, "java/lang/String"); 
jmethodID mid = (*env)->GetStaticMethodID(env, clazz, "methodName", 
"(…)…"); 
if (mid != NULL) 
(*env)->CallStatic<Type>Method(env, clazz, mid, parameters…); 
• (…)…: method signature 
• parameters: list of parameters expected by the Java* method 
• <Type>: Java method return type
25 
Throwing Java* Exceptions 
jclass clazz = 
(*env->FindClass(env, "java/lang/Exception"); 
if (clazz!=NULL) 
(*env)->ThrowNew(env, clazz, "Message"); 
The exception will be thrown only when the JNI call returns to Java*, it 
will not break the current native code execution.
26 
Configuring NDK Target ABIs 
Include all ABIs by setting APP_ABI to all in jni/Application.mk: 
APP_ABI=all 
The NDK will generate optimized code for all target ABIs 
You can also pass APP_ABI variable to ndk-build, and specify each ABI: 
ndk-build APP_ABI=x86 
all32 and all64 are also possible values. 
Build ARM64 libs 
Build x86_64 libs 
Build mips64 libs 
Build ARMv7a libs 
Build ARMv5 libs 
Build x86 libs 
Build mips libs
27 
“Fat” APKs 
By default, an APK contains libraries for every supported ABIs. 
Install lib/armeabi-v7a libs 
… … … 
Install lib/x86 libs 
Install lib/x86_64 libraries 
libs/armeabi-v7a 
libs/x86 
libs/x86_64 
… 
APK file 
Libs for the selected ABI are installed, the others remain inside the downloaded APK
28 
Multiple APKs 
Google Play* supports multiple APKs for the same application. 
What compatible APK will be chosen for a device entirely depends on the android:versionCode 
If you have multiple APKs for multiple ABIs, best is to simply prefix your current version code with a 
digit representing the ABI: 
23103310 63107310 
ARMv7 ARM64 x86 X86_64 
You can have more options for multiple APKs, here is a convention that will work if you’re using all of 
these:
29 
Uploading Multiple APKs to the store 
Switch to Advanced mode before 
uploading the second APK.
31 
Debugging with logcat 
NDK provides log API in <android/log.h>: 
int __android_log_print(int prio, const char *tag, 
const char *fmt, ...) 
Usually used through this sort of macro: 
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "APPTAG", __VA_ARGS__)) 
Usage Example: 
LOGI("accelerometer: x=%f y=%f z=%f", x, y, z);
32 
Debugging with logcat 
To get more information on native code execution: 
adb shell setprop debug.checkjni 1 
(already enabled by default in the emulator) 
And to get memory debug information (root only): 
adb shell setprop libc.debug.malloc 1 
-> leak detection 
adb shell setprop libc.debug.malloc 10 
-> overruns detection 
adb shell start/stop -> reload environment
33 
Debugging with GDB and Eclipse 
Native support must be added to your project 
Pass NDK_DEBUG=1 APP_OPTIM=debug to the ndk-build command, from the 
project properties: 
NDK_DEBUG flag is supposed to be automatically set for a 
debug build, but this is not currently the case.
34 
Debugging with GDB and Eclipse* 
When NDK_DEBUG=1 is specified, a “gdbserver” file is added to your libraries
35 
Debugging with GDB and Eclipse* 
Debug your project as a native Android* application:
36 
Debugging with GDB and Eclipse 
From Eclipse “Debug” perspective, you can manipulate breakpoints and debug 
your project 
Your application will run before the debugger is attached, hence breakpoints you 
set near application launch will be ignored
37 
GCC Flags 
ifeq ($(TARGET_ARCH_ABI),x86) 
LOCAL_CFLAGS += -ffast-math -mtune=atom -mssse3 -mfpmath=sse 
else 
LOCAL_CFLAGS += ... 
endif 
To optimize for Intel Silvermont Microarchitecture (available starting with NDK r9 gcc-4.8 
toolchain): 
LOCAL_CFLAGS += -O3 -ffast-math -mtune=slm -msse4.2 -mfpmath=sse 
ffast-math influence round-off of fp arithmetic and so breaks strict IEEE 
compliance 
The other optimizations are totally safe 
Add -ftree-vectorizer-verbose to get a vectorization report 
Optimization Notice 
Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These 
optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any 
optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. 
Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides 
for more information regarding the specific instruction sets covered by this notice. 
Notice revision #20110804
38 
Vectorization 
SIMD instructions up to SSSE3 available on current Intel® Atom™ processor based platforms, 
Intel® SSE4.2 on the Intel Silvermont Microarchitecture 
127 0 
On ARM*, you can get vectorization through the ARM NEON* instructions 
Two classic ways to use these instructions: 
• Compiler auto-vectorization 
• Compiler intrinsics 
Optimization Notice 
Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These 
optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any 
optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. 
Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides 
for more information regarding the specific instruction sets covered by this notice. 
Notice revision #20110804 
SSSE3, SSE4.2 
Vector size: 128 bit 
Data types: 
• 8, 16, 32, 64 bit integer 
• 32 and 64 bit float 
VL: 2, 4, 8, 16 
X2 
Y2 
X2◦Y2 
X1 
Y1 
X1◦Y1 
X4 
Y4 
X4◦Y4 
X3 
Y3 
X3◦Y3
39 
Android* Studio NDK support 
• Having .c(pp) sources inside jni folder ? 
• ndk-build automatically called on a generated Android.mk, ignoring any existing .mk 
• All configuration done through build.gradle (moduleName, ldLibs, cFlags, stl) 
• You can change that to continue relying on your own Makefiles: 
http://ph0b.com/android-studio-gradle-and-ndk-integration/ 
• Having .so files to integrate ? 
• Copy them to jniLibs folder or integrate them from a .jar library 
• Use flavors to build one APK per architecture with a computed versionCode 
http://tools.android.com/tech-docs/new-build-system/tips
40 
Intel INDE 
40 
A productivity tool built with today’s developer in mind. 
 IDE support: Eclipse*, Microsoft Visual Studio* 
 Host support: Microsoft Windows* 7-8.1 
 Target support: Android 4.3 & up devices on ARM* and Intel® 
Architecture, Microsoft Windows* 7-8.1 devices on Intel® 
Architecture 
Increasing productivity at every step along the development chain 
Create Compile Analyze & Debug Ship 
Environment set-up & maintenance 
 Frame Debugger 
 System Analyzer 
 Platform Analyzer 
 Frame Analyzer 
 Compute Code 
Builder 
 Android Versions 4.3 
& up, Intel® 
Architecture & ARM* 
devices. 
 Microsoft Windows* 
7-8.1 Intel® 
Architecture devices 
 GNU C++ 
Compiler 
 Intel® C++ 
Compiler 
 Compute Code 
Builder 
 Media 
 Threading 
 Compute Code 
Builder 
Download: intel.com/software/inde
41 
Intel® System Studio 2014 
41 
Integrated software tool suite that provides 
deep system-wide insights to help: 
 Accelerate Time-to-Market 
 Strengthen System Reliability 
 Boost Power Efficiency and Performance 
UPDATED NEW 
DEBUGGERS 
System Application 
ANALYZERS 
Power & 
Performance 
Memory & 
Threading 
COMPILER & 
LIBRARIES 
C/C++ 
Compiler 
Signal, media, Data & 
Math Processing 
JTAG 
Interface1 
System & Application code running Linux*, Wind River Linux*, Android*, Tizen* or 
Wind River VxWorks* 
Embedded or Mobile System 
1 Optional 
UPDATED 
NEW 
Intel® Quark
42 
Some last comments 
• In Application.mk, ANDROID_PLATFORM value should be the same as your 
minSdkLevel 
• With Android L, JNI is more strict than before: 
• pay attention to object references and methods mapping
Q&A 
alexander.weggerle@intel.com
44 
3rd party libraries x86 support 
Game engines/libraries with x86 support: 
• Havok Anarchy SDK: android x86 target available 
• Unreal Engine 3: android x86 target available 
• Marmalade: android x86 target available 
• Cocos2Dx: set APP_ABI in Application.mk 
• FMOD: x86 lib already included, set ABIs in Application.mk 
• AppGameKit: x86 lib included, set ABIs in Application.mk 
• libgdx: x86 supported by default in latest releases 
• AppPortable: x86 support now available 
• Adobe Air: x86 support in beta releases 
• … 
No x86 support but works on consumer devices: 
• Corona 
• Unity

More Related Content

What's hot (20)

PDF
Android NDK and the x86 Platform
Sebastian Mauer
 
PPTX
Native development kit (ndk) introduction
Rakesh Jha
 
PDF
NDK Programming in Android
Arvind Devaraj
 
PDF
Introduction to the Android NDK
Sebastian Mauer
 
PPTX
Object Oriented Code RE with HexraysCodeXplorer
Alex Matrosov
 
PDF
Advanced Evasion Techniques by Win32/Gapz
Alex Matrosov
 
PPTX
How to implement a simple dalvik virtual machine
Chun-Yu Wang
 
PDF
Android NDK: Entrando no Mundo Nativo
Eduardo Carrara de Araujo
 
PPTX
Проведение криминалистической экспертизы и анализа руткит-программ на примере...
Alex Matrosov
 
PDF
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
CODE WHITE GmbH
 
PDF
Eric Lafortune - Fighting application size with ProGuard and beyond
GuardSquare
 
PDF
[COSCUP 2021] A trip about how I contribute to LLVM
Douglas Chen
 
PDF
ADB(Android Debug Bridge): How it works?
Tetsuyuki Kobayashi
 
PPTX
How to Build & Use OpenCL on OpenCV & Android NDK
Industrial Technology Research Institute (ITRI)(工業技術研究院, 工研院)
 
PPTX
OpenDaylight Developer Experience 2.0
Michael Vorburger
 
PDF
"The OpenCV Open Source Computer Vision Library: Latest Developments," a Pres...
Edge AI and Vision Alliance
 
PDF
Hierarchy Viewer Internals
Kyungmin Lee
 
PDF
Facebook Glow Compiler のソースコードをグダグダ語る会
Mr. Vengineer
 
PDF
Toward dynamic analysis of obfuscated android malware
ZongXian Shen
 
PDF
Jollen's Presentation: Introducing Android low-level
Jollen Chen
 
Android NDK and the x86 Platform
Sebastian Mauer
 
Native development kit (ndk) introduction
Rakesh Jha
 
NDK Programming in Android
Arvind Devaraj
 
Introduction to the Android NDK
Sebastian Mauer
 
Object Oriented Code RE with HexraysCodeXplorer
Alex Matrosov
 
Advanced Evasion Techniques by Win32/Gapz
Alex Matrosov
 
How to implement a simple dalvik virtual machine
Chun-Yu Wang
 
Android NDK: Entrando no Mundo Nativo
Eduardo Carrara de Araujo
 
Проведение криминалистической экспертизы и анализа руткит-программ на примере...
Alex Matrosov
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
CODE WHITE GmbH
 
Eric Lafortune - Fighting application size with ProGuard and beyond
GuardSquare
 
[COSCUP 2021] A trip about how I contribute to LLVM
Douglas Chen
 
ADB(Android Debug Bridge): How it works?
Tetsuyuki Kobayashi
 
OpenDaylight Developer Experience 2.0
Michael Vorburger
 
"The OpenCV Open Source Computer Vision Library: Latest Developments," a Pres...
Edge AI and Vision Alliance
 
Hierarchy Viewer Internals
Kyungmin Lee
 
Facebook Glow Compiler のソースコードをグダグダ語る会
Mr. Vengineer
 
Toward dynamic analysis of obfuscated android malware
ZongXian Shen
 
Jollen's Presentation: Introducing Android low-level
Jollen Chen
 

Similar to Using the android ndk - DroidCon Paris 2014 (20)

PPTX
Getting started with the NDK
Kirill Kounik
 
PDF
Getting Native with NDK
ナム-Nam Nguyễn
 
PPTX
Advance Android Application Development
Ramesh Prasad
 
PDF
Android on IA devices and Intel Tools
Xavier Hallade
 
PDF
DLL Design with Building Blocks
Max Kleiner
 
PPT
Native Android for Windows Developers
Yoss Cohen
 
PDF
Working with the AOSP - Linaro Connect Asia 2013
Opersys inc.
 
PPTX
Android ndk
Sentinel Solutions Ltd
 
ODT
Cross-compilation native sous android
Thierry Gayet
 
PPTX
Android NDK Intro
Giles Payne
 
PPTX
Cross Platform App Development with C++
Joan Puig Sanz
 
PPTX
Android ndk - Introduction
Rakesh Jha
 
PDF
Running native code on Android #OSDCfr 2012
Cédric Deltheil
 
PDF
LinkedIn - Disassembling Dalvik Bytecode
Alain Leon
 
PDF
NDK Primer (AnDevCon Boston 2014)
Ron Munitz
 
PDF
109842496 jni
Vishal Singh
 
PDF
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
BeMyApp
 
PDF
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
PPTX
C# Production Debugging Made Easy
Alon Fliess
 
PDF
Investigation report on 64 bit support and some of new features in aosp master
hidenorly
 
Getting started with the NDK
Kirill Kounik
 
Getting Native with NDK
ナム-Nam Nguyễn
 
Advance Android Application Development
Ramesh Prasad
 
Android on IA devices and Intel Tools
Xavier Hallade
 
DLL Design with Building Blocks
Max Kleiner
 
Native Android for Windows Developers
Yoss Cohen
 
Working with the AOSP - Linaro Connect Asia 2013
Opersys inc.
 
Cross-compilation native sous android
Thierry Gayet
 
Android NDK Intro
Giles Payne
 
Cross Platform App Development with C++
Joan Puig Sanz
 
Android ndk - Introduction
Rakesh Jha
 
Running native code on Android #OSDCfr 2012
Cédric Deltheil
 
LinkedIn - Disassembling Dalvik Bytecode
Alain Leon
 
NDK Primer (AnDevCon Boston 2014)
Ron Munitz
 
109842496 jni
Vishal Singh
 
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
BeMyApp
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
C# Production Debugging Made Easy
Alon Fliess
 
Investigation report on 64 bit support and some of new features in aosp master
hidenorly
 
Ad

More from Paris Android User Group (20)

PDF
Workshop: building your mobile backend with Parse - Droidcon Paris2014
Paris Android User Group
 
PDF
Workshop: Amazon developer ecosystem - DroidCon Paris2014
Paris Android User Group
 
PDF
Extending your apps to wearables - DroidCon Paris 2014
Paris Android User Group
 
PDF
Scaling android development - DroidCon Paris 2014
Paris Android User Group
 
PDF
Ingredient of awesome app - DroidCon Paris 2014
Paris Android User Group
 
PDF
Framing the canvas - DroidCon Paris 2014
Paris Android User Group
 
PDF
Deep dive into android restoration - DroidCon Paris 2014
Paris Android User Group
 
PDF
Archos Android based connected home solution - DroidCon Paris 2014
Paris Android User Group
 
PDF
Porting VLC on Android - DroidCon Paris 2014
Paris Android User Group
 
PDF
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
Paris Android User Group
 
PDF
Buildsystem.mk - DroidCon Paris 2014
Paris Android User Group
 
PDF
maximize app engagement and monetization - DroidCon Paris 2014
Paris Android User Group
 
PPTX
Holo material design transition - DroidCon Paris 2014
Paris Android User Group
 
PPTX
Death to passwords - DroidCon Paris 2014
Paris Android User Group
 
PPTX
Google glass droidcon - DroidCon Paris 2014
Paris Android User Group
 
PPTX
Embedded webserver implementation and usage - DroidCon Paris 2014
Paris Android User Group
 
PDF
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
Paris Android User Group
 
PDF
What's new in android 4.4 - Romain Guy & Chet Haase
Paris Android User Group
 
PDF
Efficient Image Processing - Nicolas Roard
Paris Android User Group
 
PDF
Build a user experience by Eyal Lezmy
Paris Android User Group
 
Workshop: building your mobile backend with Parse - Droidcon Paris2014
Paris Android User Group
 
Workshop: Amazon developer ecosystem - DroidCon Paris2014
Paris Android User Group
 
Extending your apps to wearables - DroidCon Paris 2014
Paris Android User Group
 
Scaling android development - DroidCon Paris 2014
Paris Android User Group
 
Ingredient of awesome app - DroidCon Paris 2014
Paris Android User Group
 
Framing the canvas - DroidCon Paris 2014
Paris Android User Group
 
Deep dive into android restoration - DroidCon Paris 2014
Paris Android User Group
 
Archos Android based connected home solution - DroidCon Paris 2014
Paris Android User Group
 
Porting VLC on Android - DroidCon Paris 2014
Paris Android User Group
 
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
Paris Android User Group
 
Buildsystem.mk - DroidCon Paris 2014
Paris Android User Group
 
maximize app engagement and monetization - DroidCon Paris 2014
Paris Android User Group
 
Holo material design transition - DroidCon Paris 2014
Paris Android User Group
 
Death to passwords - DroidCon Paris 2014
Paris Android User Group
 
Google glass droidcon - DroidCon Paris 2014
Paris Android User Group
 
Embedded webserver implementation and usage - DroidCon Paris 2014
Paris Android User Group
 
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
Paris Android User Group
 
What's new in android 4.4 - Romain Guy & Chet Haase
Paris Android User Group
 
Efficient Image Processing - Nicolas Roard
Paris Android User Group
 
Build a user experience by Eyal Lezmy
Paris Android User Group
 
Ad

Recently uploaded (20)

PDF
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
PDF
2025-07-15 EMEA Volledig Inzicht Dutch Webinar
ThousandEyes
 
PDF
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PDF
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PDF
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
PDF
visibel.ai Company Profile – Real-Time AI Solution for CCTV
visibelaiproject
 
PDF
Rethinking Security Operations - Modern SOC.pdf
Haris Chughtai
 
PDF
Agentic Artificial Intelligence (AI) and its growing impact on business opera...
Alakmalak Technologies Pvt. Ltd.
 
PPTX
Earn Agentblazer Status with Slack Community Patna.pptx
SanjeetMishra29
 
PDF
Trading Volume Explained by CIFDAQ- Secret Of Market Trends
CIFDAQ
 
PDF
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
2025-07-15 EMEA Volledig Inzicht Dutch Webinar
ThousandEyes
 
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
visibel.ai Company Profile – Real-Time AI Solution for CCTV
visibelaiproject
 
Rethinking Security Operations - Modern SOC.pdf
Haris Chughtai
 
Agentic Artificial Intelligence (AI) and its growing impact on business opera...
Alakmalak Technologies Pvt. Ltd.
 
Earn Agentblazer Status with Slack Community Patna.pptx
SanjeetMishra29
 
Trading Volume Explained by CIFDAQ- Secret Of Market Trends
CIFDAQ
 
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 

Using the android ndk - DroidCon Paris 2014

  • 1. Using the Android* Native Development Kit (NDK) Alexander Weggerle, Technical Consultant Engineer, Intel Corporation
  • 2. 2 1 in 1,374,589 2
  • 3. 3 Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Debug and Optimization • Some more tips • Q&A
  • 4. 4 Android* Native Development Kit (NDK) What is it?  Build scripts/toolkit to incorporate native code in Android* apps via the Java Native Interface (JNI) Why use it?  Performance  e.g., complex algorithms, multimedia applications, games  Differentiation  app that takes advantage of direct CPU/HW access  e.g., using SSSE3 for optimization  Fluid and lag-free animations  Software code reuse Why not use it?  Performance improvement isn’t always guaranteed, in contrary to the added complexity
  • 5. 5 NDK Application Development C/C++ Code Makefile ndk-build Mix with Java* GDB debug SDK APIs Java Framework Using JNI JNI Native Libs Android* Application NDK APIs Bionic C Library
  • 6. 6 Compatibility with Standard C/C++ Bionic C Library:  Lighter than standard GNU C Library  Not POSIX compliant  pthread support included, but limited  No System-V IPCs  Access to Android* system properties Bionic is not binary-compatible with the standard C library It means you generally need to (re)compile everything using the Android NDK toolchain
  • 7. 7 Android* C++ Support By default, system is used. It lacks:  Standard C++ Library support (except some headers)  C++ exceptions support  RTTI support Fortunately, you have other libs available with the NDK: Runtime Exceptions RTTI STL system No No No gabi++ Yes Yes No stlport Yes Yes Yes gnustl Yes Yes Yes libc++ Yes Yes Yes Choose which library to compile against in your Makefile (Application.mk file): APP_STL := gnustl_shared Postfix the runtime with _static or _shared For using C++ features, you also need to enable these in your Makefile: LOCAL_CPP_FEATURES += exceptions rtti
  • 8. 8 Installing the Android* NDK NDK is a platform dependent archive: It provides: PSI TS PIDs  A build environment  Android* headers and libraries  Documentation and samples (these are very useful) You can integrate it with Eclipse ADT:
  • 9. 9 Manually Adding Native Code to an Android* Project Standard Android* Project Structure Native Sources - JNI Folder 1. Create JNI folder for native sources 3. Create Android.mk Makefile 2. Reuse or create native 4. Build Native libraries using NDK-BUILD script. c/c++ sources NDK-BUILD will automatically create ABI libs folders.
  • 10. 10 Adding NDK Support to your Eclipse Android* Project
  • 11. 11 Android* NDK Samples Sample App Type hello-jni Call a native function written in C from Java*. bitmap-plasma Access an Android* Bitmap object from C. san-angeles EGL and OpenGL* ES code in C. hello-gl2 EGL setup in Java and OpenGL ES code in C. native-activity C only OpenGL sample (no Java, uses the NativeActivity class). two-libs Integrates more than one library …
  • 12. 12 Focus on Native Activity Only native code in the project android_main() entry point running in its own thread Event loop to get input data and frame drawing messages /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state);
  • 13. 13 Integrating Native Functions with Java* Declare native methods in your Android* application (Java*) using the ‘native’ keyword: public native String stringFromJNI(); PSI TS PIDs Provide a native shared library built with the NDK that contains the methods used by your application: libMyLib.so Your application must load the shared library (before use… during class load for example): static { System.loadLibrary("MyLib"); } There is two ways to associate your native code to the Java methods: javah and JNI_OnLoad
  • 14. 14 Javah Method “javah” helps automatically generate the appropriate JNI header stubs based on the Java* source files from the compiled Java classes files: Example: > javah –d jni –classpath bin/classes com.example.hellojni.HelloJni Generates com_example_hellojni_HelloJni.h file with this definition: JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv *, jobject);
  • 15. 15 Javah Method C function that will be automatically mapped: jstring Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env, jobject thiz ) { return (*env)->NewStringUTF(env, "Hello from JNI !"); } ... { ... tv.setText( stringFromJNI() ); ... } public native String stringFromJNI(); static { System.loadLibrary("hello-jni"); }
  • 16. 19 Memory Handling of Java* Objects Memory handling of Java* objects is done by the JVM: • You only deal with references to these objects • Each time you get a reference, you must not forget to delete it after use • local references are automatically deleted when the native call returns to Java • References are local by default • Global references are only created by NewGlobalRef()
  • 17. 20 Creating a Java* String C: jstring string = (*env)->NewStringUTF(env, "new Java String"); C++: jstring string = env->NewStringUTF("new Java String"); Memory is handled by the JVM, jstring is always a reference. You can call DeleteLocalRef() on it once you finished with it. Main difference with compiling JNI code in C or in C++ is the nature of “env” as you can see it here. Remember that otherwise, the API is the same.
  • 18. 21 Getting a C/C++ String from Java* String const char *nativeString = (*env)- >GetStringUTFChars(javaString, null); … (*env)->ReleaseStringUTFChars(env, javaString, nativeString); //more secure int tmpjstrlen = env->GetStringUTFLength(tmpjstr); char* fname = new char[tmpjstrlen + 1]; env->GetStringUTFRegion(tmpjstr, 0, tmpjstrlen, fname); fname[tmpjstrlen] = 0; … delete fname;
  • 19. 22 Handling Java* Exceptions // call to java methods may throw Java exceptions jthrowable ex = (*env)->ExceptionOccurred(env); if (ex!=NULL) { (*env)->ExceptionClear(env); // deal with exception } (*env)->DeleteLocalRef(env, ex);
  • 20. 24 Calling Java* Methods On an object instance: jclass clazz = (*env)->GetObjectClass(env, obj); jmethodID mid = (*env)->GetMethodID(env, clazz, "methodName", "(…)…"); if (mid != NULL) (*env)->Call<Type>Method(env, obj, mid, parameters…); Static call: jclass clazz = (*env)->FindClass(env, "java/lang/String"); jmethodID mid = (*env)->GetStaticMethodID(env, clazz, "methodName", "(…)…"); if (mid != NULL) (*env)->CallStatic<Type>Method(env, clazz, mid, parameters…); • (…)…: method signature • parameters: list of parameters expected by the Java* method • <Type>: Java method return type
  • 21. 25 Throwing Java* Exceptions jclass clazz = (*env->FindClass(env, "java/lang/Exception"); if (clazz!=NULL) (*env)->ThrowNew(env, clazz, "Message"); The exception will be thrown only when the JNI call returns to Java*, it will not break the current native code execution.
  • 22. 26 Configuring NDK Target ABIs Include all ABIs by setting APP_ABI to all in jni/Application.mk: APP_ABI=all The NDK will generate optimized code for all target ABIs You can also pass APP_ABI variable to ndk-build, and specify each ABI: ndk-build APP_ABI=x86 all32 and all64 are also possible values. Build ARM64 libs Build x86_64 libs Build mips64 libs Build ARMv7a libs Build ARMv5 libs Build x86 libs Build mips libs
  • 23. 27 “Fat” APKs By default, an APK contains libraries for every supported ABIs. Install lib/armeabi-v7a libs … … … Install lib/x86 libs Install lib/x86_64 libraries libs/armeabi-v7a libs/x86 libs/x86_64 … APK file Libs for the selected ABI are installed, the others remain inside the downloaded APK
  • 24. 28 Multiple APKs Google Play* supports multiple APKs for the same application. What compatible APK will be chosen for a device entirely depends on the android:versionCode If you have multiple APKs for multiple ABIs, best is to simply prefix your current version code with a digit representing the ABI: 23103310 63107310 ARMv7 ARM64 x86 X86_64 You can have more options for multiple APKs, here is a convention that will work if you’re using all of these:
  • 25. 29 Uploading Multiple APKs to the store Switch to Advanced mode before uploading the second APK.
  • 26. 31 Debugging with logcat NDK provides log API in <android/log.h>: int __android_log_print(int prio, const char *tag, const char *fmt, ...) Usually used through this sort of macro: #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "APPTAG", __VA_ARGS__)) Usage Example: LOGI("accelerometer: x=%f y=%f z=%f", x, y, z);
  • 27. 32 Debugging with logcat To get more information on native code execution: adb shell setprop debug.checkjni 1 (already enabled by default in the emulator) And to get memory debug information (root only): adb shell setprop libc.debug.malloc 1 -> leak detection adb shell setprop libc.debug.malloc 10 -> overruns detection adb shell start/stop -> reload environment
  • 28. 33 Debugging with GDB and Eclipse Native support must be added to your project Pass NDK_DEBUG=1 APP_OPTIM=debug to the ndk-build command, from the project properties: NDK_DEBUG flag is supposed to be automatically set for a debug build, but this is not currently the case.
  • 29. 34 Debugging with GDB and Eclipse* When NDK_DEBUG=1 is specified, a “gdbserver” file is added to your libraries
  • 30. 35 Debugging with GDB and Eclipse* Debug your project as a native Android* application:
  • 31. 36 Debugging with GDB and Eclipse From Eclipse “Debug” perspective, you can manipulate breakpoints and debug your project Your application will run before the debugger is attached, hence breakpoints you set near application launch will be ignored
  • 32. 37 GCC Flags ifeq ($(TARGET_ARCH_ABI),x86) LOCAL_CFLAGS += -ffast-math -mtune=atom -mssse3 -mfpmath=sse else LOCAL_CFLAGS += ... endif To optimize for Intel Silvermont Microarchitecture (available starting with NDK r9 gcc-4.8 toolchain): LOCAL_CFLAGS += -O3 -ffast-math -mtune=slm -msse4.2 -mfpmath=sse ffast-math influence round-off of fp arithmetic and so breaks strict IEEE compliance The other optimizations are totally safe Add -ftree-vectorizer-verbose to get a vectorization report Optimization Notice Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision #20110804
  • 33. 38 Vectorization SIMD instructions up to SSSE3 available on current Intel® Atom™ processor based platforms, Intel® SSE4.2 on the Intel Silvermont Microarchitecture 127 0 On ARM*, you can get vectorization through the ARM NEON* instructions Two classic ways to use these instructions: • Compiler auto-vectorization • Compiler intrinsics Optimization Notice Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision #20110804 SSSE3, SSE4.2 Vector size: 128 bit Data types: • 8, 16, 32, 64 bit integer • 32 and 64 bit float VL: 2, 4, 8, 16 X2 Y2 X2◦Y2 X1 Y1 X1◦Y1 X4 Y4 X4◦Y4 X3 Y3 X3◦Y3
  • 34. 39 Android* Studio NDK support • Having .c(pp) sources inside jni folder ? • ndk-build automatically called on a generated Android.mk, ignoring any existing .mk • All configuration done through build.gradle (moduleName, ldLibs, cFlags, stl) • You can change that to continue relying on your own Makefiles: http://ph0b.com/android-studio-gradle-and-ndk-integration/ • Having .so files to integrate ? • Copy them to jniLibs folder or integrate them from a .jar library • Use flavors to build one APK per architecture with a computed versionCode http://tools.android.com/tech-docs/new-build-system/tips
  • 35. 40 Intel INDE 40 A productivity tool built with today’s developer in mind.  IDE support: Eclipse*, Microsoft Visual Studio*  Host support: Microsoft Windows* 7-8.1  Target support: Android 4.3 & up devices on ARM* and Intel® Architecture, Microsoft Windows* 7-8.1 devices on Intel® Architecture Increasing productivity at every step along the development chain Create Compile Analyze & Debug Ship Environment set-up & maintenance  Frame Debugger  System Analyzer  Platform Analyzer  Frame Analyzer  Compute Code Builder  Android Versions 4.3 & up, Intel® Architecture & ARM* devices.  Microsoft Windows* 7-8.1 Intel® Architecture devices  GNU C++ Compiler  Intel® C++ Compiler  Compute Code Builder  Media  Threading  Compute Code Builder Download: intel.com/software/inde
  • 36. 41 Intel® System Studio 2014 41 Integrated software tool suite that provides deep system-wide insights to help:  Accelerate Time-to-Market  Strengthen System Reliability  Boost Power Efficiency and Performance UPDATED NEW DEBUGGERS System Application ANALYZERS Power & Performance Memory & Threading COMPILER & LIBRARIES C/C++ Compiler Signal, media, Data & Math Processing JTAG Interface1 System & Application code running Linux*, Wind River Linux*, Android*, Tizen* or Wind River VxWorks* Embedded or Mobile System 1 Optional UPDATED NEW Intel® Quark
  • 37. 42 Some last comments • In Application.mk, ANDROID_PLATFORM value should be the same as your minSdkLevel • With Android L, JNI is more strict than before: • pay attention to object references and methods mapping
  • 39. 44 3rd party libraries x86 support Game engines/libraries with x86 support: • Havok Anarchy SDK: android x86 target available • Unreal Engine 3: android x86 target available • Marmalade: android x86 target available • Cocos2Dx: set APP_ABI in Application.mk • FMOD: x86 lib already included, set ABIs in Application.mk • AppGameKit: x86 lib included, set ABIs in Application.mk • libgdx: x86 supported by default in latest releases • AppPortable: x86 support now available • Adobe Air: x86 support in beta releases • … No x86 support but works on consumer devices: • Corona • Unity

Editor's Notes

  • #30: The APK information on the right will be the same if you are in advanced mode or simple mode. You can have the feeling it’s replacing your previous APK at this moment. In fact, if you are in advanced mode it will only be added to your APKs list as you want it.