SlideShare a Scribd company logo
ADVANCE ANDROID APPLICATION DEVELOPMENTRamesh Prasad
INTRODUCTION TO NATIVE DEVELOPMENT
Native DevelopmentAndroid applications run in the Dalvik virtual machine. The Native Development allows you to implement parts of your applications using native-code languages such as C and C++. This can provide benefits to certain classes of applications, in the form of reuse of existing code and in some cases increased speed.
When to Develop in Native CodeThe Native Development will not benefit most applications. As a developer, you need to balance its benefits against its drawbacks; notably, using native code does not result in an automatic performance increase, but always increases application complexity. In general, you should only use native code if it is essential to your application, not just because you prefer to program in C/C++.
When to Develop in Native CodeTypical good candidates for the NDK are self-contained, CPU-intensive operations that don't allocate much memory, such as signal processing, physics simulation, and so on. Simply re-coding a method to run in C usually does not result in a large performance increase. When examining whether or not you should develop in native code, think about your requirements and see if the Android framework APIs provide the functionality that you need. The NDK can, however, can be an effective way to reuse a large corpus of existing C/C++ code.
When to Develop in Native CodeWrite your application using the Android framework and use JNI to access the APIs provided by the Android NDK. This technique allows you to take advantage of the convenience of the Android framework, but still allows you to write native code when necessary. You can install applications that use native code through the JNI on devices that run Android 1.5 or later.
Bionic
BionicGoogle developed a custom library for the C compiler (libc) called Bionic. This was necessary for three main reasons: License: they wanted to keep GPL out of user-space. Bionic code uses the BSD license. Size: the library has to be loaded in each process, so it needs to be small. Bionic is about 200K, or half the size of glibc (the GNU version of libc). Speed: limited CPU power means it needs to be fast. Bionic has a small size and fast code paths, including a very fast and small custom pthread implementation.
BionicBionic has built-in support for important Android-specific services such as system properties and logging. It doesn’t support certain POSIX features, like C++ exceptions and wide chars, which were not needed on Android. Thus it’s not quite compatible with the gnu libc. All native code must be compiled against bionic, not glibc.
Architecture SupportThe library is written to support ARM CPUs, though some x86 support is also present.There is no support for other CPU architectures
C++ SupportSo what is different about the Bionic libc versus glibc? The most striking differences are in the C++ supportC++No C++ exceptionsNo STLPthread
C++ exceptionsThe Bionic libc routines do not handle C++ exceptions.They neither throw exceptions themselves, nor will they pass exceptions from a called function back through to their caller. So for example, if the cmp() routine passed to qsort() throws an exception the caller of qsort() will not see it.Support for C++ exceptions adds significant overhead to function calls, even just to pass thrown exceptions back to the caller. As Android's primary programming language is Java, which handles exceptions entirely within the runtime package, the designers chose to omit the lower level exception support.
STLThere is no C++ Standard Template Library included. Developers are free supply their own, such as the free SGI implementation.
PthreadThe pthread implementation appears to be completely new and developed by Google specifically for Android. It is, quite deliberately, not a complete implementation of POSIX pthreads. It implements those features necessary to support threads in the Dalvik JVM, and only selectively thereafter.
PthreadMutexes, rwlocks, condvars, etc are all implemented using kernel futexes, which makes the user space implementation impressively simple.There is no pthread_cancel(). Threads can exit, but can not be killed by another thread.There is no pthread_atfork(). This routine is useful if you're going to fork from a threaded process, allowing cleanups of resources which should not be held in the child.Thread local storage is implemented, with up to 64 keys handled. Android reserves several of these for its own use: the per-thread id and errno, as well as two variables related to OpenGLPOSIX realtime thread extensions like pthread_attr_{set,get}inheritsched and pthread_attr_{set,get}scope are not implemented.
DEVELOPING WITH NDK
NDKThe Android NDK is a toolset that lets you embed components that make use of native code in your Android applications.The NDK provides:A set of tools and build files used to generate native code libraries from C and C++ sourcesA way to embed the corresponding native libraries into an application package file (.apk) that can be deployed on Android devicesA set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5. Documentation, samples, and tutorials
NDKThe latest release of the NDK supports these ARM instruction sets:ARMv5TE (including Thumb-1 instructions)ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for NEON/VFPv3-D32 instructions)x86 instructions
LibrariesIt provides a set of system headers for stable native APIs that are guaranteed to be supported in all later releases of the platform:libc (C library) headerslibm (math library) headersJNI interface headerslibz (Zlib compression) headersliblog (Android logging) headerOpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headerslibjnigraphics (Pixel buffer access) header (for Android 2.2 and above).A Minimal set of headers for C++ supportOpenSL ES native audio librariesAndroid native application APIS
Build SystemThe NDK also provides a build system that lets you work efficiently with your sources, without having to handle the toolchain/platform/CPU/ABI details. You create very short build files to describe which sources to compile and which Android application will use them — the build system compiles the sources and places the shared libraries directly in your application project.
DevelopingInstallationIntroductionManaging projectsBuilding & RunningDebugging
LabHello World Tutorial\android-ndk-r4\samples\hello-jni
NATIVE APPLICATION DEVELOPMENT
Application Structure Java CodeJava Native InterfaceNative Code(Shared Object)Native Code(Static Library)
Java CodeYour application's source code will declare one or more methods with the 'native' keyword to indicate that they are implemented through native code. E.g.:      		native String  stringFromJNI(); You must provide a native shared library that contains the implementation of these methods, which will be packaged into your application's .apk. This library must be named according to standard  Unix conventions as lib<something>.so, and shall contain a standard JNI entry point (more on this later). For example:libhello-jni.so Your application must explicitely load the library. For example, to load it at application startup, simply add the following to its source code: static {System.loadLibrary("hello-jni");    }    Note that you should not use the 'lib' prefix and '.so' suffix here.
C/C++ CodeMust implement a JNI Interface#include <jni.h>jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobjectthiz ){    return (*env)->NewStringUTF(env, "Hello from JNI !");}JNIEnv *: A pointer to the JNI environment. This pointer is a handle to the current thread in the Java virtual machine, and contains mapping and other hosuekeeping information. jobject: A reference to the method that called this native code. If the calling method is static, this parameter would be type jclass instead of jobject. jstring: The value returned by the native method.Package & Java FilenameFunction name
Passing StringsThe String object in the Java language, which is represented as jstring in Java Native Interface (JNI), is a 16 bit unicode string. In C a string is by default constructed from 8 bit characters. So, to access a Java language String object passed to a C or C++ function or return a C or C++ string to a Java language method, you need to use JNI conversion functions in your native method implementation. The following C JNI function converts an array of C characters to a jstring:(*env)->NewStringUTF(env, lastfile) Iscopy – returns the result JNI_TRUE if it made a local copy of the jstring or JNI_FALSE otherwise
Passing StringsTo let the Java virtual machine know you are finished with the UTF representation, call the ReleaseStringUTFChars conversion function as shown below. The second argument is the original jstring value used to construct the UTF representation, and the third argument is the reference to the local representation of that String. 	(*env)-ReleaseStringUTFChars(env, name, mfile);
Passing Values/Arrays
MakefileAn Android.mk file is written to describe your sources to the build system. More specifically:The file is really a tiny GNU Makefile fragment that will be parsed one or more times by the build system.The file syntax is designed to allow you to group your   sources into 'modules'. A module is one of the following:    a static library    a shared library Only shared libraries will be installed/copied to your application package. Static libraries can be used to generate shared libraries though. You can define one or more modules in each Android.mk file, and you can use the same source file in several modules.The build system handles many details for you. For example, you   don't need to list header files or explicit dependencies between   generated files in your Android.mk. The NDK build system will   compute these automatically for you.
Makefile
MakefileLOCAL_PATH := $(call my-dir)An Android.mk file must begin with the definition of the LOCAL_PATH variable. It is used to locate source files in the development tree. In this example, the macro function 'my-dir', provided by the build system, is used to return the path of the current directory (i.e. the directory containing the Android.mk file itself). include $(CLEAR_VARS)The CLEAR_VARS variable is provided by the build system and points to a special GNU Makefile that will clear many LOCAL_XXX variables for you (e.g. LOCAL_MODULE, LOCAL_SRC_FILES, LOCAL_STATIC_LIBRARIES, etc...), with the exception of LOCAL_PATH. LOCAL_MODULE := hello-jniThe LOCAL_MODULE variable must be defined to identify each module you describe in your Android.mk. The name must be *unique* and not contain any spaces. Note that the build system will automatically add proper prefix and suffix to the corresponding generated file. In other words, a shared library module named 'foo' will generate 'libfoo.so'.LOCAL_SRC_FILES := hello-jni.cThe LOCAL_SRC_FILES variables must contain a list of C and/or C++ source files that will be built and assembled into a module. Note that you should not list header and included files here, because the build system will compute dependencies automatically for you; just list the source files that will be passed directly to a compiler, and you should be good.
NDK-provided function macrosThe following are GNU Make 'function' macros, and must be evaluated by using '$(call <function>)'. They return textual information.my-dir		Returns the path of the current Android.mk's directory, relative to the top of the NDK build system. This is useful to define LOCAL_PATH at the start of your Android.mk as with:        LOCAL_PATH := $(call my-dir)
NDK-provided function macrosall-subdir-makefiles	Returns a list of Android.mk located in all sub-directories of the current 'my-dir' path. For example, consider the following hierarchy:sources/foo/Android.mksources/foo/lib1/Android.mksources/foo/lib2/Android.mkIf sources/foo/Android.mk contains the single line:        include $(call all-subdir-makefiles)Then it will include automatically sources/foo/lib1/Android.mk and	sources/foo/lib2/Android.mk This function can be used to provide deep-nested source directory hierarchies to the build system. Note that by default, the NDK will only look for files in sources/*/Android.mk
NDK-provided function macrosthis-makefile    Returns the path of the current Makefile (i.e. where the function    is called).parent-makefile    Returns the path of the parent Makefile in the inclusion tree,    i.e. the path of the Makefile that included the current one.grand-parent-makefile    Guess what...
Module-description variables
LabHello JNI\android-ndk-r4\samples\hello-jni
USING PROCESSOR FEATURES
USING PROCESSOR FEATURESThis NDK provides a small library named "cpufeatures" that can be used at runtime to detect the target device's CPU family and the optional features it supports.
UsageThe library is available from sources/cpufeatures. It provides an Android.mk build script that can be used to build it as a static library. To use it, you must:include '$(NDK_ROOT)/sources/cpufeatures/Android.mk' at the start or end of your Android.mk file. add '$(NDK_ROOT)/sources/cpufeatures' to your LOCAL_C_INCLUDES definition. add 'cpufeatures' to your LOCAL_STATIC_LIBRARIES definition when building your final shared library.  your source code can then #include <cpu-features.h> to compile against it.
Usage231
FeaturesTwo functions are provided for now:AndroidCpuFamilyandroid_getCpuFamily();uint64_t   android_getCpuFeatures();AndroidCpuFamilyReturns the target device's CPU Family as an enum. For now, the only supported family is ANDROID_CPU_FAMILY_ARM.
Featuresandroid_getCpuFeatures() Returns the set of optional features supported by the device's CPU. The result is a set of bit-flags, each corresponding to one CPU Family-specific optional feature.Currently, only the following flags are defined, for the ARM CPU Family:ANDROID_CPU_ARM_FEATURE_ARMv7Indicates that the device's CPU supports the ARMv7-A instruction set as supported by the "armeabi-v7a" abiANDROID_CPU_ARM_FEATURE_VFPv3 Indicates that the device's CPU supports the VFPv3 hardware FPU instruction set extension. Due to the definition of 'armeabi-v7a', this will always be the case if ANDROID_CPU_ARM_FEATURE_ARMv7 is returned.ANDROID_CPU_ARM_FEATURE_NEONIndicates that the device's CPU supports the ARM Advanced SIMD (a.k.a. NEON) vector instruction set extension.

More Related Content

PPTX
Android Development with Kotlin course
GoogleDevelopersLeba
 
PDF
Mobile Programming - 1 Introduction
AndiNurkholis1
 
PPTX
Introduction to Android programming
Sirwan Afifi
 
PDF
International Journal of Engineering Research and Development
IJERD Editor
 
PPT
Intro to Android Programming
Peter van der Linden
 
PPT
Synapseindia android app programming
Tarunsingh198
 
PPTX
Compilation Of C/C++ program in Android
rahulverma1080
 
PPTX
Mobile Application Development
Abhi583497
 
Android Development with Kotlin course
GoogleDevelopersLeba
 
Mobile Programming - 1 Introduction
AndiNurkholis1
 
Introduction to Android programming
Sirwan Afifi
 
International Journal of Engineering Research and Development
IJERD Editor
 
Intro to Android Programming
Peter van der Linden
 
Synapseindia android app programming
Tarunsingh198
 
Compilation Of C/C++ program in Android
rahulverma1080
 
Mobile Application Development
Abhi583497
 

What's hot (20)

PPTX
2018 top ide's for andriod development
Qamar Abbas
 
PPTX
Android study jams 1
NancyMariaAS
 
PPTX
Python Integrated Development Environment
TikendraPandey
 
PDF
JyothishNewResume5exp
Jyothish menon
 
PPTX
Android Project Presentation
Laxmi Kant Yadav
 
PPTX
Ide description
Nidhi Baranwal
 
PPTX
Selenium web driver_2.0_presentation
sayhi2sudarshan
 
PPTX
Choose flutter
SamuelAdetunji2
 
PDF
The Ring programming language version 1.3 book - Part 4 of 88
Mahmoud Samir Fayed
 
PPT
Android software stack
Soba Arjun
 
PDF
Swift vs flutter pixel values technolabs
Pixel Values Technolabs
 
PPTX
Android Workshop Day 1 Part 2
Ahsanul Karim
 
PPTX
Java Programming (M&M)
mafffffe19
 
PPTX
Introduction to flutter's basic concepts
Kumaresh Chandra Baruri
 
PPT
Android overview
Alexey Ustenko
 
PPTX
Browser core red bus presentation
redBus India
 
PPTX
Dload mobile development
Sayed Ahmed
 
PPTX
iOS Development, with Swift and XCode
Wan Leung Wong
 
PPTX
Cross platform app development with flutter
Hwan Jo
 
2018 top ide's for andriod development
Qamar Abbas
 
Android study jams 1
NancyMariaAS
 
Python Integrated Development Environment
TikendraPandey
 
JyothishNewResume5exp
Jyothish menon
 
Android Project Presentation
Laxmi Kant Yadav
 
Ide description
Nidhi Baranwal
 
Selenium web driver_2.0_presentation
sayhi2sudarshan
 
Choose flutter
SamuelAdetunji2
 
The Ring programming language version 1.3 book - Part 4 of 88
Mahmoud Samir Fayed
 
Android software stack
Soba Arjun
 
Swift vs flutter pixel values technolabs
Pixel Values Technolabs
 
Android Workshop Day 1 Part 2
Ahsanul Karim
 
Java Programming (M&M)
mafffffe19
 
Introduction to flutter's basic concepts
Kumaresh Chandra Baruri
 
Android overview
Alexey Ustenko
 
Browser core red bus presentation
redBus India
 
Dload mobile development
Sayed Ahmed
 
iOS Development, with Swift and XCode
Wan Leung Wong
 
Cross platform app development with flutter
Hwan Jo
 
Ad

Viewers also liked (20)

PDF
Android Protips: Advanced Topics for Expert Android App Developers
Reto Meier
 
PPTX
Presentation on Android operating system
Salma Begum
 
PPT
Android ppt
blogger at indiandswad
 
PPTX
New features in android m upload
Bin Yang
 
PPSX
Android OS and its Features
Harshad Lokhande
 
PPTX
Application component
home
 
PDF
Android vs i os features
Guang Ying Yuan
 
PDF
Api List September
chrisvanceeastbound
 
PDF
Android Development: Build Android App from Scratch
Taufan Erfiyanto
 
PPTX
Android ppt
Sunil Kumar
 
PDF
Advance Android Programming - learning beyond basics
ayman diab
 
ODP
Non Conventional Android Programming (English)
Davide Cerbo
 
PDF
Advance Android application development workshop day 1
cresco
 
PDF
Android Workshop 2013
Junda Ong
 
PPT
Memory problems in android programming
AiTi Education
 
PPTX
Software proposal on android
Kamrul Chowdhury
 
PDF
Asynchronous Programming in Android
John Pendexter
 
PDF
Android UI Reference
GauntFace
 
PDF
Advance Android application development workshop day 3
cresco
 
PDF
Android Components
Aatul Palandurkar
 
Android Protips: Advanced Topics for Expert Android App Developers
Reto Meier
 
Presentation on Android operating system
Salma Begum
 
New features in android m upload
Bin Yang
 
Android OS and its Features
Harshad Lokhande
 
Application component
home
 
Android vs i os features
Guang Ying Yuan
 
Api List September
chrisvanceeastbound
 
Android Development: Build Android App from Scratch
Taufan Erfiyanto
 
Android ppt
Sunil Kumar
 
Advance Android Programming - learning beyond basics
ayman diab
 
Non Conventional Android Programming (English)
Davide Cerbo
 
Advance Android application development workshop day 1
cresco
 
Android Workshop 2013
Junda Ong
 
Memory problems in android programming
AiTi Education
 
Software proposal on android
Kamrul Chowdhury
 
Asynchronous Programming in Android
John Pendexter
 
Android UI Reference
GauntFace
 
Advance Android application development workshop day 3
cresco
 
Android Components
Aatul Palandurkar
 
Ad

Similar to Advance Android Application Development (20)

PDF
Android on IA devices and Intel Tools
Xavier Hallade
 
PPTX
Using the android ndk - DroidCon Paris 2014
Paris Android User Group
 
PDF
Android Native Development Kit
Peter R. Egli
 
PPT
Introduction to .net
Karthika Parthasarathy
 
PDF
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
PDF
Getting Native with NDK
ナム-Nam Nguyễn
 
PPTX
Getting started with the NDK
Kirill Kounik
 
PPT
01 Introduction to programming
maznabili
 
DOCX
C# tutorial
sarangowtham_gunnam
 
PDF
LinkedIn - Disassembling Dalvik Bytecode
Alain Leon
 
PDF
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Tim Burks
 
PPT
Introduction to Programming Lesson 01
A-Tech and Software Development
 
PDF
.NET Core, ASP.NET Core Course, Session 3
Amin Mesbahi
 
PDF
Dotnet basics
Mir Majid
 
PPTX
Programming
mafffffe19
 
PDF
(1) c sharp introduction_basics_dot_net
Nico Ludwig
 
PPTX
Android NDK
Sentinel Solutions Ltd
 
DOCX
The seven pillars of aspnet
Nethaji Naidu
 
PDF
Android develop guideline
Kan-Han (John) Lu
 
PPTX
Android ndk - Introduction
Rakesh Jha
 
Android on IA devices and Intel Tools
Xavier Hallade
 
Using the android ndk - DroidCon Paris 2014
Paris Android User Group
 
Android Native Development Kit
Peter R. Egli
 
Introduction to .net
Karthika Parthasarathy
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
Getting Native with NDK
ナム-Nam Nguyễn
 
Getting started with the NDK
Kirill Kounik
 
01 Introduction to programming
maznabili
 
C# tutorial
sarangowtham_gunnam
 
LinkedIn - Disassembling Dalvik Bytecode
Alain Leon
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Tim Burks
 
Introduction to Programming Lesson 01
A-Tech and Software Development
 
.NET Core, ASP.NET Core Course, Session 3
Amin Mesbahi
 
Dotnet basics
Mir Majid
 
Programming
mafffffe19
 
(1) c sharp introduction_basics_dot_net
Nico Ludwig
 
The seven pillars of aspnet
Nethaji Naidu
 
Android develop guideline
Kan-Han (John) Lu
 
Android ndk - Introduction
Rakesh Jha
 

More from Ramesh Prasad (6)

PDF
Multimedia on android
Ramesh Prasad
 
PPTX
Managing sales using CRM
Ramesh Prasad
 
PDF
Signal processing in smartphones - 4G perspective
Ramesh Prasad
 
PPTX
Android Application Development
Ramesh Prasad
 
PPTX
Sdk For Firmware Development
Ramesh Prasad
 
PPTX
De Interlacing Techniques
Ramesh Prasad
 
Multimedia on android
Ramesh Prasad
 
Managing sales using CRM
Ramesh Prasad
 
Signal processing in smartphones - 4G perspective
Ramesh Prasad
 
Android Application Development
Ramesh Prasad
 
Sdk For Firmware Development
Ramesh Prasad
 
De Interlacing Techniques
Ramesh Prasad
 

Advance Android Application Development

  • 1. ADVANCE ANDROID APPLICATION DEVELOPMENTRamesh Prasad
  • 3. Native DevelopmentAndroid applications run in the Dalvik virtual machine. The Native Development allows you to implement parts of your applications using native-code languages such as C and C++. This can provide benefits to certain classes of applications, in the form of reuse of existing code and in some cases increased speed.
  • 4. When to Develop in Native CodeThe Native Development will not benefit most applications. As a developer, you need to balance its benefits against its drawbacks; notably, using native code does not result in an automatic performance increase, but always increases application complexity. In general, you should only use native code if it is essential to your application, not just because you prefer to program in C/C++.
  • 5. When to Develop in Native CodeTypical good candidates for the NDK are self-contained, CPU-intensive operations that don't allocate much memory, such as signal processing, physics simulation, and so on. Simply re-coding a method to run in C usually does not result in a large performance increase. When examining whether or not you should develop in native code, think about your requirements and see if the Android framework APIs provide the functionality that you need. The NDK can, however, can be an effective way to reuse a large corpus of existing C/C++ code.
  • 6. When to Develop in Native CodeWrite your application using the Android framework and use JNI to access the APIs provided by the Android NDK. This technique allows you to take advantage of the convenience of the Android framework, but still allows you to write native code when necessary. You can install applications that use native code through the JNI on devices that run Android 1.5 or later.
  • 8. BionicGoogle developed a custom library for the C compiler (libc) called Bionic. This was necessary for three main reasons: License: they wanted to keep GPL out of user-space. Bionic code uses the BSD license. Size: the library has to be loaded in each process, so it needs to be small. Bionic is about 200K, or half the size of glibc (the GNU version of libc). Speed: limited CPU power means it needs to be fast. Bionic has a small size and fast code paths, including a very fast and small custom pthread implementation.
  • 9. BionicBionic has built-in support for important Android-specific services such as system properties and logging. It doesn’t support certain POSIX features, like C++ exceptions and wide chars, which were not needed on Android. Thus it’s not quite compatible with the gnu libc. All native code must be compiled against bionic, not glibc.
  • 10. Architecture SupportThe library is written to support ARM CPUs, though some x86 support is also present.There is no support for other CPU architectures
  • 11. C++ SupportSo what is different about the Bionic libc versus glibc? The most striking differences are in the C++ supportC++No C++ exceptionsNo STLPthread
  • 12. C++ exceptionsThe Bionic libc routines do not handle C++ exceptions.They neither throw exceptions themselves, nor will they pass exceptions from a called function back through to their caller. So for example, if the cmp() routine passed to qsort() throws an exception the caller of qsort() will not see it.Support for C++ exceptions adds significant overhead to function calls, even just to pass thrown exceptions back to the caller. As Android's primary programming language is Java, which handles exceptions entirely within the runtime package, the designers chose to omit the lower level exception support.
  • 13. STLThere is no C++ Standard Template Library included. Developers are free supply their own, such as the free SGI implementation.
  • 14. PthreadThe pthread implementation appears to be completely new and developed by Google specifically for Android. It is, quite deliberately, not a complete implementation of POSIX pthreads. It implements those features necessary to support threads in the Dalvik JVM, and only selectively thereafter.
  • 15. PthreadMutexes, rwlocks, condvars, etc are all implemented using kernel futexes, which makes the user space implementation impressively simple.There is no pthread_cancel(). Threads can exit, but can not be killed by another thread.There is no pthread_atfork(). This routine is useful if you're going to fork from a threaded process, allowing cleanups of resources which should not be held in the child.Thread local storage is implemented, with up to 64 keys handled. Android reserves several of these for its own use: the per-thread id and errno, as well as two variables related to OpenGLPOSIX realtime thread extensions like pthread_attr_{set,get}inheritsched and pthread_attr_{set,get}scope are not implemented.
  • 17. NDKThe Android NDK is a toolset that lets you embed components that make use of native code in your Android applications.The NDK provides:A set of tools and build files used to generate native code libraries from C and C++ sourcesA way to embed the corresponding native libraries into an application package file (.apk) that can be deployed on Android devicesA set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5. Documentation, samples, and tutorials
  • 18. NDKThe latest release of the NDK supports these ARM instruction sets:ARMv5TE (including Thumb-1 instructions)ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for NEON/VFPv3-D32 instructions)x86 instructions
  • 19. LibrariesIt provides a set of system headers for stable native APIs that are guaranteed to be supported in all later releases of the platform:libc (C library) headerslibm (math library) headersJNI interface headerslibz (Zlib compression) headersliblog (Android logging) headerOpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headerslibjnigraphics (Pixel buffer access) header (for Android 2.2 and above).A Minimal set of headers for C++ supportOpenSL ES native audio librariesAndroid native application APIS
  • 20. Build SystemThe NDK also provides a build system that lets you work efficiently with your sources, without having to handle the toolchain/platform/CPU/ABI details. You create very short build files to describe which sources to compile and which Android application will use them — the build system compiles the sources and places the shared libraries directly in your application project.
  • 24. Application Structure Java CodeJava Native InterfaceNative Code(Shared Object)Native Code(Static Library)
  • 25. Java CodeYour application's source code will declare one or more methods with the 'native' keyword to indicate that they are implemented through native code. E.g.: native String stringFromJNI(); You must provide a native shared library that contains the implementation of these methods, which will be packaged into your application's .apk. This library must be named according to standard Unix conventions as lib<something>.so, and shall contain a standard JNI entry point (more on this later). For example:libhello-jni.so Your application must explicitely load the library. For example, to load it at application startup, simply add the following to its source code: static {System.loadLibrary("hello-jni"); } Note that you should not use the 'lib' prefix and '.so' suffix here.
  • 26. C/C++ CodeMust implement a JNI Interface#include <jni.h>jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobjectthiz ){ return (*env)->NewStringUTF(env, "Hello from JNI !");}JNIEnv *: A pointer to the JNI environment. This pointer is a handle to the current thread in the Java virtual machine, and contains mapping and other hosuekeeping information. jobject: A reference to the method that called this native code. If the calling method is static, this parameter would be type jclass instead of jobject. jstring: The value returned by the native method.Package & Java FilenameFunction name
  • 27. Passing StringsThe String object in the Java language, which is represented as jstring in Java Native Interface (JNI), is a 16 bit unicode string. In C a string is by default constructed from 8 bit characters. So, to access a Java language String object passed to a C or C++ function or return a C or C++ string to a Java language method, you need to use JNI conversion functions in your native method implementation. The following C JNI function converts an array of C characters to a jstring:(*env)->NewStringUTF(env, lastfile) Iscopy – returns the result JNI_TRUE if it made a local copy of the jstring or JNI_FALSE otherwise
  • 28. Passing StringsTo let the Java virtual machine know you are finished with the UTF representation, call the ReleaseStringUTFChars conversion function as shown below. The second argument is the original jstring value used to construct the UTF representation, and the third argument is the reference to the local representation of that String. (*env)-ReleaseStringUTFChars(env, name, mfile);
  • 30. MakefileAn Android.mk file is written to describe your sources to the build system. More specifically:The file is really a tiny GNU Makefile fragment that will be parsed one or more times by the build system.The file syntax is designed to allow you to group your sources into 'modules'. A module is one of the following: a static library a shared library Only shared libraries will be installed/copied to your application package. Static libraries can be used to generate shared libraries though. You can define one or more modules in each Android.mk file, and you can use the same source file in several modules.The build system handles many details for you. For example, you don't need to list header files or explicit dependencies between generated files in your Android.mk. The NDK build system will compute these automatically for you.
  • 32. MakefileLOCAL_PATH := $(call my-dir)An Android.mk file must begin with the definition of the LOCAL_PATH variable. It is used to locate source files in the development tree. In this example, the macro function 'my-dir', provided by the build system, is used to return the path of the current directory (i.e. the directory containing the Android.mk file itself). include $(CLEAR_VARS)The CLEAR_VARS variable is provided by the build system and points to a special GNU Makefile that will clear many LOCAL_XXX variables for you (e.g. LOCAL_MODULE, LOCAL_SRC_FILES, LOCAL_STATIC_LIBRARIES, etc...), with the exception of LOCAL_PATH. LOCAL_MODULE := hello-jniThe LOCAL_MODULE variable must be defined to identify each module you describe in your Android.mk. The name must be *unique* and not contain any spaces. Note that the build system will automatically add proper prefix and suffix to the corresponding generated file. In other words, a shared library module named 'foo' will generate 'libfoo.so'.LOCAL_SRC_FILES := hello-jni.cThe LOCAL_SRC_FILES variables must contain a list of C and/or C++ source files that will be built and assembled into a module. Note that you should not list header and included files here, because the build system will compute dependencies automatically for you; just list the source files that will be passed directly to a compiler, and you should be good.
  • 33. NDK-provided function macrosThe following are GNU Make 'function' macros, and must be evaluated by using '$(call <function>)'. They return textual information.my-dir Returns the path of the current Android.mk's directory, relative to the top of the NDK build system. This is useful to define LOCAL_PATH at the start of your Android.mk as with: LOCAL_PATH := $(call my-dir)
  • 34. NDK-provided function macrosall-subdir-makefiles Returns a list of Android.mk located in all sub-directories of the current 'my-dir' path. For example, consider the following hierarchy:sources/foo/Android.mksources/foo/lib1/Android.mksources/foo/lib2/Android.mkIf sources/foo/Android.mk contains the single line: include $(call all-subdir-makefiles)Then it will include automatically sources/foo/lib1/Android.mk and sources/foo/lib2/Android.mk This function can be used to provide deep-nested source directory hierarchies to the build system. Note that by default, the NDK will only look for files in sources/*/Android.mk
  • 35. NDK-provided function macrosthis-makefile Returns the path of the current Makefile (i.e. where the function is called).parent-makefile Returns the path of the parent Makefile in the inclusion tree, i.e. the path of the Makefile that included the current one.grand-parent-makefile Guess what...
  • 39. USING PROCESSOR FEATURESThis NDK provides a small library named "cpufeatures" that can be used at runtime to detect the target device's CPU family and the optional features it supports.
  • 40. UsageThe library is available from sources/cpufeatures. It provides an Android.mk build script that can be used to build it as a static library. To use it, you must:include '$(NDK_ROOT)/sources/cpufeatures/Android.mk' at the start or end of your Android.mk file. add '$(NDK_ROOT)/sources/cpufeatures' to your LOCAL_C_INCLUDES definition. add 'cpufeatures' to your LOCAL_STATIC_LIBRARIES definition when building your final shared library. your source code can then #include <cpu-features.h> to compile against it.
  • 42. FeaturesTwo functions are provided for now:AndroidCpuFamilyandroid_getCpuFamily();uint64_t android_getCpuFeatures();AndroidCpuFamilyReturns the target device's CPU Family as an enum. For now, the only supported family is ANDROID_CPU_FAMILY_ARM.
  • 43. Featuresandroid_getCpuFeatures() Returns the set of optional features supported by the device's CPU. The result is a set of bit-flags, each corresponding to one CPU Family-specific optional feature.Currently, only the following flags are defined, for the ARM CPU Family:ANDROID_CPU_ARM_FEATURE_ARMv7Indicates that the device's CPU supports the ARMv7-A instruction set as supported by the "armeabi-v7a" abiANDROID_CPU_ARM_FEATURE_VFPv3 Indicates that the device's CPU supports the VFPv3 hardware FPU instruction set extension. Due to the definition of 'armeabi-v7a', this will always be the case if ANDROID_CPU_ARM_FEATURE_ARMv7 is returned.ANDROID_CPU_ARM_FEATURE_NEONIndicates that the device's CPU supports the ARM Advanced SIMD (a.k.a. NEON) vector instruction set extension.
  • 47. MonkeyThe infinite monkey theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. adb shell monkey -p com.example.android.apis -v 500